在EF中以1 ... 0,1关系插入新行的问题

时间:2018-09-11 06:14:24

标签: c# sql-server asp.net-mvc entity-framework-6

我有两个表,Person和Employee,并且我分别分别创建了1 .. 0,1关系。 Person表中的PersonId已定义身份1. Employee表中的EmployeeId未定义身份。

enter image description here

当我使用SQL Studio将新行插入Person表时,一切正常,但是当我尝试使用Entity Framework插入数据时,出现错误:

  

无法为表“人员”中的身份列插入显式值   当IDENTITY_INSERT设置为OFF时。

PersonId未明确定义,保存时为0

请注意,插入新人员行可以正常工作,而无需与员工建立联系。

我错过了明显的东西还是我的方法完全错误?可悲的是,谷歌搜索根本没有帮助。

  

编辑:我已经找到解决方法,但是我将为人们添加实体代码   面临同样的问题。

人员实体:

public partial class Person
{
    public Person()
    {
    }

    [Key]
    public int PersonId { get; set; }
    ...
    public virtual Employee Employee { get; set; }

员工实体:

public partial class Employee
{
    public Employee()
    {
    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int EmployeeId { get; set; }
    ...
    public Data.Dal.Person Person { get; set; }

在上下文中定义的关系:

modelBuilder.Entity<Employee>()
   .HasRequired(s => s.Person)
   .WithRequiredPrincipal(ad => ad.Employee);

3 个答案:

答案 0 :(得分:0)

您是否会在ID列上自动递增?在您的SQL数据库中定义。 如果是这种情况,请尝试使用以下方法装饰您实体的相应属性 DatabaseGenerated.Identity属性。

答案 1 :(得分:0)

我找到了解决方案。我正在使用代码优先方法来生成数据对象模型。 EF将此关系创建为:

    modelBuilder.Entity<Employee>()
        .HasRequired(s => s.Person)
        .WithRequiredPrincipal(ad => ad.Employee);

通过EF定义Employee是主要引用的类,这是错误的。我将引用类更改为Person,到目前为止一切正常。

正确的关系:

    modelBuilder.Entity<Employee>()
        .HasRequired(s => s.Person)
        .WithRequiredDependent(ad => ad.Employee);

有关推荐和在回答中被引用的更多信息:Ef code first diference between principle and dependent

答案 2 :(得分:0)

我认为您可以使用SQL Server解决问题,在SQL Server中与员工建立联系,然后尝试再次插入新人员。