0

由于我对 EntityFramwork 没有那么丰富的经验,因此我遇到了问题。我需要跟踪哪个用户创建了事务以及哪个用户修改了该事务。这意味着我有两个具有相同类的属性。

以下是事务类中的属性列表:

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.
4

1 回答 1

1

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

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


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

当然 HasOptional 也可以是 hasrequired。

于 2013-10-11T21:45:30.197 回答