代码优先 - 具有不同于类的名称的导航属性

时间:2013-07-12 16:10:08

标签: asp.net-mvc-4 ef-code-first

我有几种情况,我的导航属性在一个类中重复,或者我不希望它与它所代表的类具有相同的名称。例如:

public class Employee 
{   
   public Guid EmployeeId { get; set; }
   public string Name { get; set; }
}

public class Project
{
   public Guid ProjectId { get; set; }
   public DateTime Start { get; set; }

   public Guid ResponsibleId { get; set; }
   public virtual Employee Responsible { get; set; }

   public Guid OwnerId { get; set; }
   public virtual Employee Owner { get; set; }
}

使用EF Code First时,它会弄乱外键,创建具有不同名称的新外键。我该如何处理?

非常感谢!

2 个答案:

答案 0 :(得分:1)

这应该有所帮助:

public class Employee 
{   
  public Guid EmployeeId { get; set; }
  public string Name { get; set; }

  public virtual ICollection<Project> ResponsibleProjects { get; set; }
  public virtual ICollection<Project> OwnedProjects { get; set; }
}

public class Project
{
  public Guid ProjectId { get; set; }
  public DateTime Start { get; set; }

  public Guid ResponsibleId { get; set; }
  public virtual Employee Responsible { get; set; }

  public Guid OwnerId { get; set; }
  public virtual Employee Owner { get; set; }
}

public YourContext : DbContext 
{

  protected override void OnModelCreating(DbModelBuilder modelBuilder)
  {
     modelBuilder.Entity<Project>()
         .HasRequired(p => p.Owner)
         .WithMany(e => e.OwnedProjects )  
         .HasForeignKey(p => p.OwnerId );

     modelBuilder.Entity<Project>()
         .HasRequired(p => p.Responsible)
         .WithMany(e => e.ResponsibleProjects )  
         .HasForeignKey(p => p.ResponsibleId );

     base.OnModelCreating(modelBuilder);
  }

注意如何为两端定义关系以及如何指出哪个确切字段用作外键。

答案 1 :(得分:0)

我最终这样做了,这有效:

public class Employee 
{   
   public Guid EmployeeId { get; set; }
   public string Name { get; set; }
}

public class Project
{
   public Guid ProjectId { get; set; }
   public DateTime Start { get; set; }

   public Guid ResponsibleId { get; set; }
   [ForeignKey("ResponsibleId")]
   public virtual Employee Responsible { get; set; }

   public Guid OwnerId { get; set; }
   [ForeignKey("OwnerId")]
   public virtual Employee Owner { get; set; }
}

感谢Wiktor提供导致解决方案的评论。