One to many relationships not working at EF
In my MVC project, I am using EF Code First. I have 2 tables. Table 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; }
}
}
Table2:
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; }
}
}
Now I want them to have a one to many attitude. But it doesn't work. What is the problem? I am using migration mode in ef.
+3
source to share
1 answer
Have you tried mapping relationships to Fluent API?
In your DbContext class, you must override the OnModelCreating method and create a link 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 block of code might solve your problem.
UPDATE
I think you should use data annotations on the virtual property to make it work.
In the Lead class:
[ForeignKey("NamePrefixID")]
public virtual NamePrefixes NamePrefixes { get; set; }
You may try?
Hello
0
source to share