ASP.NET MVC不止一次使用与属性相同的复杂类型

时间:2014-02-20 11:20:49

标签: c# asp.net-mvc entity-framework asp.net-mvc-4

我创建了一个模型,该模型使用名为Operator的类两次,一次命名为CreatedBy,再次命名为ModifiedBy。当我为这些属性创建标识字段时,EF会创建新的标识字段。

public int CreatedBy_OperatorId { get; set; }

[Display(Name = "Created By")]
public virtual Operator CreatedBy { get; set; }

public int ModifiedBy_OperatorId { get; set; }

[Display(Name = "Created By")]
public virtual Operator ModifiedBy { get; set; }

我的问题是如何强制EF使用我的身份字段?

2 个答案:

答案 0 :(得分:1)

试试这个:

public int CreatedBy_OperatorId { get; set; }

[Display(Name = "Created By")]
[ForeignKey("CreatedBy_OperatorId")]
public virtual Operator CreatedBy { get; set; }

public int ModifiedBy_OperatorId { get; set; }

[Display(Name = "Created By")]
[ForeignKey("ModifiedBy_OperatorId")]
public virtual Operator ModifiedBy { get; set; }

答案 1 :(得分:0)

Influencing foreign key column naming in EF code first (CTP5)似乎有答案。

首先在代码中我需要确保指定了外键,然后我可以使用HasColumnName函数定义键的名称。

        builder.Entity<ContactRecord>()
            .HasRequired(p => p.CreatedBy)
            .WithMany()
            .HasForeignKey(p => p.CreatedBy_OperatorId)
            .WillCascadeOnDelete(false);
        builder.Entity<ContactRecord>()
            .Property(p => p.CreatedBy_OperatorId)
            .HasColumnName("CreatedBy_OperatorId");

        builder.Entity<ContactRecord>()
            .HasRequired(p => p.ModifiedBy)
            .WithMany()
            .HasForeignKey(p => p.ModifiedBy_OperatorId)
            .WillCascadeOnDelete(false);
        builder.Entity<ContactRecord>()
            .Property(p => p.ModifiedBy_OperatorId)
            .HasColumnName("ModifiedBy_OperatorId");