实体框架:具有相同类问题的两个属性

时间:2013-10-08 23:41:01

标签: c# .net entity-framework

由于我对EntityFramwork不太熟悉,我遇到了问题。我需要跟踪哪个用户创建了事务以及哪个用户修改了该事务。这意味着我有具有相同类别的两个属性。

以下是Transaction Class中的属性列表:

public virtual System.DateTime DateCreated { get; set; }
public virtual System.DateTime DateModified { get; set; }
public virtual bool IsDeleted { get; set; }
public virtual bool IsActive { get; set; }
public virtual string Description { get; set; }

public virtual User CreatedBy { get; set; }
public virtual User ModifiedBy { get; set; }

每当调用context.SaveChanges()时,我都会遇到以下异常:

Unable to determine the principal end of an association between the types 'Model.Entities.User' and 'Model.Entities.User'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

1 个答案:

答案 0 :(得分:1)

您应该覆盖dbcontext类中的OnModelCreating方法并添加以下代码

 modelBuilder.Entity<Transaction)()
 .HasOptional<User>(x => x.CreatedBy);


 modelBuilder.Entity<Transaction)()
 .HasOptional<User>(x => x.ModifiedBy);

当然也可以提供HasOptional。