1

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

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 时,它会弄乱外键,创建具有不同名称的新键。我该如何处理?

非常感谢!

4

2 回答 2

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

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

于 2013-07-12T18:18:37.900 回答
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 提供解决方案的评论。

于 2013-07-12T20:19:52.773 回答