在我的 MVC 项目中,我使用的是 EF Code First。 我有 2 张 table 。 表一:
namespace CL_AHR_CRM.Models
{
public partial class Leads
{
[Key]
public int LeadID { get; set; }
[NotMapped]
public string FullName { get { return FirstName + " " + LastName; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int NamePrefixID { get; set; }
public virtual NamePrefixes NamePrefixes { get; set; }
}
}
表 2:
namespace CL_AHR_CRM.Models
{
public partial class NamePrefixes
{
[Key]
public int NamePrefixID { get; set; }
public string Prefix { get; set; }
public virtual ICollection<Leads> Leads { get; set; }
}
}
现在我想让他们建立一对多的关系。但它不起作用。 哪里有问题? 我在 ef 中使用迁移模式。
最佳答案
您是否尝试过使用 Fluent API 映射关系?
在您的 DbContext 类中,您应该覆盖 OnModelCreating 方法并生成如下关系:
public class MyEntities : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Leads>().HasRequired(m => m.NamePrefixes).WithMany(m => m.Leads).HasForeignKey(m => m.NamePrefixID);
}
}
此代码块可能会解决您的问题。
更新:
我认为你应该在虚拟属性中使用数据注释来使其工作。
在 Lead 类中:
[ForeignKey("NamePrefixID")]
public virtual NamePrefixes NamePrefixes { get; set; }
你能试试吗?
问候
关于c# - 一对多关系在 EF 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31135683/