3

请原谅我是 EF 的菜鸟,首先是代码。我的问题是我不想在模型中添加外键属性,根据 MSDN,使用 fluent 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:保存不为其关系公开外键属性的实体时发生错误。EntityEntries 属性将返回 null,因为无法将单个实体标识为异常源。通过在实体类型中公开外键属性,可以更轻松地在保存时处理异常。

有人可以帮我找出创建模型时需要进行的正确流畅调用吗?

4

1 回答 1

1

你应该使用这个:

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);
    }
}
于 2014-02-02T09:36:52.547 回答