请原谅我首先是 EF 的菜鸟。我的问题是我不想向模型添加外键属性,根据 MSDN,使用流畅的 API 没有问题,但是我无法找出当前情况的正确用法。这似乎很简单:
public class Package
{
public Package()
{
Users = new Collection<User>();
}
public Int32 Id {get; set;}
public String Name {get; set;}
public virtual User Creator {get; set;}
public virtual ICollection<User> Users {get; set;}
}
public class User
{
public Int32 Id {get; set;}
public String Name {get; set;}
}
public class PackageContext : DbContext
{
public DbSet<Package> Packages {get; set;}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Package>().HasRequired(p => p.Creator).WithMany();
modelBuilder.Entity<Package>().HasMany(p => p.Users).WithRequired().Map(c => c.MapKey("PackageId"));
base.OnModelCreating(modelBuilder);
}
}
我尝试了许多不同的流利组合,但没有一个正常工作。我得到的最常见的例外是:
System.Data.Entity.Infrastructure.DbUpdateException:保存未公开其关系的外键属性的实体时出错。属性将返回 null,因为无法将单个实体标识为异常的来源。通过在实体类型中公开外键属性,可以更轻松地在保存时处理异常。
有人可以帮我找出创建模型时需要进行的正确流畅调用吗?
你应该使用这个:
public class Package
{
public Int32 Id {get; set;}
public String Name {get; set;}
public Int32 UserId {get; set;}
public virtual User Creator {get; set;}
}
public class User
{
public User()
{
Packages = new Collection<Package>();
}
public Int32 Id {get; set;}
public String Name {get; set;}
public virtual ICollection<Package> Packages {get; set;}
}
public class PackageContext : DbContext
{
public DbSet<Package> Packages {get; set;}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Package>().HasRequired(current => current.Creator)
.WithMany(c=>c.Packages)
.HasForeignKey(c=>c.UserId)
.WillCascadeOnDelete(false);
base.OnModelCreating(modelBuilder);
}
}