一对多关系不适用于EF

本文关键字:EF 适用于 不适用 关系 一对多 | 更新日期: 2023-09-27 18:00:32

在我的MVC项目中,我使用的是EF Code First。我有两张桌子。表1:

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中使用迁移模式。

一对多关系不适用于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);
     }
}

此代码块可能会解决您的问题。

更新

我认为您应该在虚拟属性中使用数据注释来使其工作。

在铅类:

[ForeignKey("NamePrefixID")]
public virtual NamePrefixes NamePrefixes { get; set; }

你能试试吗?

问候