自动填充外键字符串字段

时间:2016-02-26 12:40:00

标签: c# entity-framework entity-framework-6

我目前正在将主键的类型从int更改为string,并相应地更改所有外键。但不幸的是,外键字段的自动填充现在不再起作用了。

旧(工作正常):

context.Employees.Add(new Employee
{
    Name = "John",
    Addresses = {new Address {Details = "10 Van Riper Rd,Montvale, NJ 07645"}}
});

新(破了):

context.Employees.Add(new Employee
{
    Id = "q123456",
    Name = "John",
    Addresses = {new Address {Details = "10 Van Riper Rd,Montvale, NJ 07645"}}
});

我收到了DbEntityValidationException,告诉我实体Address上的“EmployeeId字段是必需的”

我错过了设置或属性吗?或者这根本不可能?

有关您的信息,请参阅我的DbContext修改:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Employee>()
        .HasMany(employee => employee.Addresses)
        .WithRequired()
        .HasForeignKey(address => address.EmployeeId)
        .WillCascadeOnDelete(true);
}

0 个答案:

没有答案