我想知道在制作模型时处理关系默认值的最佳方式是什么。 (特别是 EF4)
例如,我的组织有一个默认联系人,我想知道哪一个是最好的方法。我有这两个选项(或任何其他人建议的更好的选项)
使用关系:
public class Contact
{
public int Id { get; set; }
public string FirstName { get; set; }
}
public class Organization
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Contact> Contacts { get; set; }
//Use a relationship for the default contact?
public Contact DefaultContact { get; set; }
}
使用值(value):
public class Contact
{
public int Id { get; set; }
public string FirstName { get; set; }
//Use value?
public boolean IsDefault { get; set; }
}
public class Organization
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Contact> Contacts { get; set; }
}
最佳答案
我会选择选项 1。虽然选项 2 确实更容易实现,但它不会强制执行诸如“不能有 2 个默认联系人”之类的规则。我最终得到如下内容:
public class Organization {
// ...
public virtual ICollection<Contact> { get;set; }
[ForeignKey("DefaultContactId")]
public Contact DefaultContact { get;set; }
public int? DefaultContactId { get;set; }
}
此方法有一个局限性 - 它不适用于嵌套删除(有关详细信息,请参阅 this question)。因此,您需要为一对多关系禁用 CascadeOnDelete:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Contact>().HasRequired(co => co.Organization).WithMany().WillCascadeOnDelete(false);
}
(代码未经测试完成,但应该可以工作)
另一个问题是在添加组织的同时添加默认联系人是不可能的,因为 EF 无法计算出正确的语句顺序。您需要在每个之间调用 .SaveChanges。您仍然可以使用 TransactionScope 来解决这个问题,但它并不干净:
using (var ts = new TransactionScope())
{
Organization org = new Organization
{
// ...
Contacts = new Collection<Contact>()
}
org.Contacts = new Contact() {};
orgRepo.SaveChanges();
// Now wire up the default contact
org.DefaultContact = org.Contacts.First();
orgRepo.SaveChanges();
}
关于asp.net - 处理 EF4 中模型的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11743542/