[英]Uni-directional one-to-many relationship with Code First
I have a one-to-many uni-directional relationship between Contact and Phone defined like this: 我在Contact和Phone之间有一对多的单向关系,定义如下:
class Contact {
int ContactId {get; set}
ICollection<Phone> Phones {get; set}
}
class Phone {
int PhoneId {get; set;}
string PhoneNumber {get; set;}
}
Now in the domain layer, i try to do the following: 现在在域层中,我尝试执行以下操作:
someContact.Phones.Remove(somePhone);
and when i try to call context.SaveChanges()
i get an exception because the relationship is defined as Required (eg. a phone cannot exist without a contact). 当我尝试调用context.SaveChanges()
我得到一个例外,因为关系被定义为必需(例如,没有联系人就不能存在电话)。
How can i solve this without using a foreign key or a navigation property in Phone and without the need to call DbSet<Phone>.Remove(Phone)
before calling SaveChanges()
? 如何在不使用Phone中的外键或导航属性的情况下解决此问题,而无需在调用SaveChanges()
之前调用DbSet<Phone>.Remove(Phone)
SaveChanges()
?
You basically answered your own question, as the two things you describe are separate: 您基本上回答了自己的问题,因为您描述的两件事是分开的:
There may be a clever way for EF to do this, but others have asked the same question and been presented with the answer you alluded to: EF可能有一种聪明的方式来做到这一点,但是其他人也提出了同样的问题并且提出了你提到的答案:
eg EF 4.1: Removing child object from collection does not delete it - why? 例如EF 4.1:从集合中删除子对象不会删除它 - 为什么?
There is a way to do both stapes that Matthew described in the single step. 有一种方法可以完成Matthew在一步中描述的两种镫骨。 It requires a little change in your model - you have to add foreign key to the Phone
entity and create a composite key that contains both PhoneId
and ContactId
. 它需要对您的模型进行一些更改 - 您必须将外键添加到Phone
实体并创建包含PhoneId
和ContactId
的复合键。
This makes the instance of the Phone
class tied to the instance of Contact
class. 这使得Phone
类的实例绑定到Contact
类的实例。 With these settings, when you remove a phone from the contact someContact.Phones.Remove(somePhone);
使用这些设置,当您从联系人中删除手机someContact.Phones.Remove(somePhone);
, EF removes phone from DB, because it knows that the phone can't exists without connection to that particular contact. ,EF从DB中删除手机,因为它知道如果没有连接到该特定联系人,手机就不能存在。
Models: 楷模:
public class Contact {
public int ContactId { get; set; }
public virtual ICollection<Phone> Phones { get; set; }
}
public class Phone {
public int PhoneId { get; set; }
public int ContactId { get; set; }
public string PhoneNumber { get; set; }
}
Configuration: 组态:
modelBuilder.Entity<Contact>()
.HasMany(o => o.Phones)
.WithRequired()
.HasForeignKey(f => f.ContactId)
.WillCascadeOnDelete(true);
modelBuilder.Entity<Phone>()
.HasKey(o => new { o.PhoneId, o.ContactId });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.