簡體   English   中英

一對多關系不適用於EF

[英]One to many relationship not working in EF

在我的MVC項目中,我正在使用EF Code First。 我有2張桌子。 表格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中使用遷移模式。

您是否嘗試使用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; }

你能試試嗎?

問候

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM