EF7 beta5:尝试插入子实体时出错

asp.net-core c# entity-framework-core

我使用ASP.NET5和Entity Framework 7.0.0-beta 5创建了一个API。

我有如此处所述创建的Model,DbContext和Repository,当我尝试使用子实体插入数据时,我的app会抛出异常:

“无法将值NULL插入列'Status',表'Company';列不允许空值.INSERT失败。”

代码+例外

Status属性在我的公司实体中不为null,但我不知道为什么EF无法插入子实体的值。 (在这种情况下,“1”)

这是堆栈跟踪:

   at Microsoft.Data.Entity.Relational.Update.ReaderModificationCommandBatch.Execute(RelationalTransaction transaction, IRelationalTypeMapper typeMapper, DbContext context, ILogger logger)
   at Microsoft.Data.Entity.Relational.Update.BatchExecutor.Execute(IEnumerable`1 commandBatches, IRelationalConnection connection)
   at Microsoft.Data.Entity.Relational.RelationalDataStore.SaveChanges(IReadOnlyList`1 entries)
   at Microsoft.Data.Entity.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList`1 entriesToSave)
   at Microsoft.Data.Entity.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
   at Microsoft.Data.Entity.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
   at Microsoft.Data.Entity.DbContext.SaveChanges()
   at **.Data.Repositories.CompanyRepository.Create(Company company) in D:\**.Data\Repositories\CompanyRepository.cs:line 36
   at **.API.Controllers.CompanyController.Create(Company company) in D:\**.API\Controllers\CompanyController.cs:line 48

这是代码:

的DbContext

public class MrBellhopContext : DbContext
{

    public DbSet<Company> Company { get; set; }
    public DbSet<CompanyStatus> CompanyStatus { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Company>().Table("Company");
        modelBuilder.Entity<Company>().Key(c => c.CompanyId);
        modelBuilder.Entity<Company>().Index(c => c.Name);
        modelBuilder.Entity<Company>().Reference(c => c.Status).InverseReference().ForeignKey<CompanyStatus>(cs => cs.StatusId);

        modelBuilder.Entity<CompanyStatus>().Table("CompanyStatus");
        modelBuilder.Entity<CompanyStatus>().Key(cs => cs.StatusId);

        base.OnModelCreating(modelBuilder);
    }

}

模型

public class Company
{

    public int CompanyId { get; set; }

    public string Name { get; set; }

    public string Email { get; set; }

    public CompanyStatus Status { get; set; }

    public DateTime CreatedAt { get; set; }

    public DateTime UpdatedAt { get; set; }

}

public class CompanyStatus
{

    public int StatusId { get; set; }

    public string Name { get; set; }

}

存储库 (仅创建方法)

    public int Create(Company company)
    {
        _dbcontext.Add(company);
        _dbcontext.SaveChanges();

        return company.CompanyId;
    }

有谁知道如何正确插入子实体?

热门答案

在EF7中,您需要将子对象附加到上下文中。这与EF6不同,我很确定你面临的情况。在保存之前尝试将对象附加到dbcontext。

发生在我身上,请查看此问题: https//github.com/aspnet/EntityFramework/issues/2387获取更多信息。



Related

许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow