gpt4 book ai didi

c#-4.0 - Entity Framework : Invalid column name *_ID1

转载 作者:行者123 更新时间:2023-12-02 11:19:35 28 4
gpt4 key购买 nike

我正在尝试为名为“Employee”和“Department”的几个表实现 DbContext员工和部门之间的关系是多对一的。即部门可以有很多员工。

下面是我设计的 EntityFramework 类(CodeFirst 方法)

    [Table("Employee")]
public class Employee
{
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

[Column("Name")]
public string Name { get; set; }

[Column("Department_ID")]
public int Department_ID { get; set; }

public virtual Department Department { get; set; }
}

[Table("Department")]
public class Department
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }

[Column("Name")]
public string Name { get; set; }

public virtual ICollection<Employee> Employees { get; set; }
}

在添加员工记录时,我遇到以下异常

"Invalid column name 'Department_ID1'." 

我不确定为什么 EF 指的是 Department_ID1。我需要在DbContextOnModelCreating方法中添加配置吗?

我使用的是 EF 版本 6.1.1

最佳答案

我在 EF one-many 交易中也遇到了这个问题,其中 one 有一个 Listmany 属性,而我的映射没有指定该属性。例如:

public class Notification
{
public long ID { get; set; }

public IList<NotificationRecipient> Recipients { get; set; }
}

然后

public class NotificationRecipient
{
public long ID { get; set; }

public long NotificationID { get; set; }

public Notification Notification { get; set; }
}

然后在我的映射中,导致异常的方式(不正确方式):

builder.HasOne(x => x.Notification).WithMany()
.HasForeignKey(x => x.NotificationID);

解决这个问题的方法(正确方法)是指定 WithMany 属性:

builder.HasOne(x => x.Notification).WithMany(x => x.Recipients)
.HasForeignKey(x => x.NotificationID);

关于c#-4.0 - Entity Framework : Invalid column name *_ID1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37606581/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com