简体   繁体   English

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

[英]Entity Framework: Two propertes with same class issue

As I am not so experienced with EntityFramwork, I am facing problems. 由于我对EntityFramwork的经验不足,因此遇到了问题。 I need to track which user created the Transaction and which user modified that transaction. 我需要跟踪哪个用户创建了事务,以及哪个用户修改了该事务。 This means I have two properties having the same class. 这意味着我有两个具有相同类的属性。

Here is the list of the properties in 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; }

Whenever the context.SaveChanges() is called i get the following exception: 每当调用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.

You should override the OnModelCreating method in your dbcontext class and add the following code 您应该在dbcontext类中重写OnModelCreating方法,并添加以下代码

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


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

Of course HasOptional can also be hasrequired. 当然也可以需要HasOptional。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM