كيفية إضافة / إزالة كثير لكثير من العلاقة مع إطار كيان بواسطة مفتاح الكيان؟
-
21-08-2019 - |
سؤال
وحاولت:
using (Entities e = new Entities())
{
EntityKey key = new EntityKey("Entities.Users", "UserId", 20);
User user = new User { EntityKey = key};
Role role = e.Roles.FirstOrDefault();
//role.Users.Attach(user); //throws (when uncommented...) InvalidOperationException:
//The object being attached to the source object is not attached to the same ObjectContext as the source object.
role.Users.Add(user); //throws InvalidOperationException too:
//The object cannot be added to the ObjectStateManager because it already has an EntityKey. Use ObjectContext.Attach to attach an object that has an existing key.
e.SaveChanges();
}
عند محاولة استخدام إزالة () دون استدعاء إرفاق قبل طرح أي استثناء ولكن العلاقة لا يتم حذف.
المحلول
وحاول شيئا من هذا القبيل:
User user = new User {UserId = 20};
e.AttachTo("Users", user);
Role role = e.Roles.FirstOrDefault();
role.Users.Add(user);
e.SaveChanges();
وأجد أنه من الأسهل بكثير للعمل مع الجهات العقب (مثل المستخدم أعلاه) بدلا من EntityKeys.
وانظر هذا <وأ href = "http://blogs.msdn.com/alexj/archive/2009/06/19/tip-26-how-to-avoid-database-queries-using-stub-entities. ASPX "يختلط =" نوفولو noreferrer "> بلوق وظيفة للحصول على مزيد من المعلومات حول تقنيات العقب الكيان.
ويساعد هذا الأمل
وأليكس
لا تنتمي إلى StackOverflow