当尝试向其中一个DbSet中添加新对象时,出现以下异常
保存或接受更改失败,因为存在多个实体 类型“ xxxxxxx.DbMember”具有相同的主键值。
问题似乎是由于我在EF实体和BL实体之间有一些自定义映射而引起的。这是代码段:
public partial class DbMember
{
//Member Properties
}
public partial class User
{
}
public partial class DbMember
{
public static implicit operator DbMember(User user)
{
var member = new DbMember();
//Map values
return member;
}
public static explicit operator User(DbMember member)
{
User user = new User();
return user;
}
}
public class UserService
{
public User GetUser(string userName){ //returns dbMember object }
}
public class AnotherService
{
public void Add(string userName,string desc)
{
var user = new UserService(_context).GetUser(userName);
var qb = new SomeOtherObject
{
User = user, Desc = desc
};
_dbSetOtherObject.Add(qb);
_context.DbMembers.Attach(qb.User);
_context.SaveChanges();
}
}
我可能做错了什么建议吗?