实体框架4 ctp5一个表有两个外键到同一个表

时间:2011-02-07 14:34:43

标签: entity-framework-4 entity-framework-ctp5

我有两张桌子:

用户和新闻。表新闻有列id,名称,createdby,modifiedby。表用户具有列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");
    }
}

1 个答案:

答案 0 :(得分: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);                        
    }
}