2011-02-07 86 views
1

我有兩個表:實體框架4 ctp5一個表有兩個外鍵給同一個表

用戶和新聞。表格新聞具有列ID,名稱,創建者,修改者。表用戶具有列標識和名稱。表新聞引用表用戶由外鍵創建並修改。我使用 實體框架4 ctp5。我嘗試訪問createdby或modifiedby屬性,但出現錯誤:無效的列名稱「UserId1」,無效的列名稱「UserId2」。有人可以解釋我做錯了什麼嗎?

public class News 
{ 
    // Primitive properties 

    public int ID { get; set; } 
    public string Name { get; set; } 
    public System.Guid UserId { get; set; } 
    public System.Guid UserId1 { get; set; } 

    // Navigation properties 

    public virtual User User { get; set; } 
    public virtual User User1 { get; set; } 

} 

public class User 
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 
} 

public partial class SomeEntities : DbContext 
{ 
    public SomeEntities() : base("name=SomeEntities"){ } 

    public DbSet<User> Users { get; set; } 
    public DbSet<News> News { get; set; } 

    protected override void OnModelCreating(ModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<News>().Property(i => i.UserId).HasColumnName("CreatedBy"); 
     modelBuilder.Entity<News>().Property(i => i.UserId1).HasColumnName("ModifiedBy"); 
    } 
} 

回答

2

下面的對象模型給你所期望的結果(我改名的屬性只是爲了使其更具可讀性):

public class News 
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 
    public Guid CreatedBy { get; set; } 
    public Guid ModifiedBy { get; set; } 
    public virtual User CreatedByUser { get; set; } 
    public virtual User ModifiedByUser { get; set; } 
} 

public class User 
{ 
    public Guid ID { get; set; } 
    public string Name { get; set; } 
} 

public class Ctp5Context : DbContext 
{ 
    public DbSet<User> Users { get; set; } 
    public DbSet<News> News { get; set; } 
    protected override void OnModelCreating(ModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<News>() 
        .HasRequired(n => n.CreatedByUser) 
        .WithMany() 
        .HasForeignKey(n => n.CreatedBy); 

     modelBuilder.Entity<News>() 
        .HasRequired(n => n.ModifiedByUser) 
        .WithMany() 
        .HasForeignKey(n => n.ModifiedBy) 
        .WillCascadeOnDelete(false);       
    } 
} 
相關問題