一对多关系在EF

时间:2015-06-30 10:21:40

标签: c# entity-framework ef-code-first one-to-many ef-migrations

在我的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。

中使用迁移模式

1 个答案:

答案 0 :(得分:0)

Did you try map the relationship with Fluent API?

In your DbContext class, you should override the OnModelCreating method and generate the relationship like this:

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);
     }
}

This code block may solve your problem.

UPDATE:

I think you should use data annotations in the virtual property to make it work.

In Lead class:

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

Can you try it?

Regards