EF每次引用一个时都会创建一个新的UserProfile?

我的问题是,以下代码不仅创建了ProtectedPassword(应该如此),而且还创建了插入其中的所有者,即使该所有者已存在。

UserProfile user = PublicUtility.GetAccount(User.Identity.Name); //gets an existing UserProfile ProtectedPassword pw = new ProtectedPassword(model.Name, user, model.Password); ProtectedPassword.Create(pw); 

因此,在创建新的ProtectedPassword之后,我最终得到了一个新的UserProfile(具有与前一个相同的值,除了新ID)。

我已经在这个问题上乱了几个小时了,如果有人可以帮助我,我会很感激!

顺便说一句,我使用ASP.NET MVC4和EF Code First。

首先,实体:ProtectedPassword:

  [Table("ProtectedPassword")] public class ProtectedPassword : ProtectedProperty { [Required] [MinLength(3)] [MaxLength(20)] public string Password { get; set; } private ProtectedPassword() { } public ProtectedPassword(string name, UserProfile owner, string password) { Name = name; Owner = owner; Password = password; SubId = PublicUtility.GenerateRandomString(8, 0); Type = ProtectedPropertyType.Password; } public static bool Create(ProtectedPassword pw) { try { using (MediaProfitsDb db = new MediaProfitsDb()) { db.ProtectedPasswords.Add(pw); db.SaveChanges(); return true; } } catch { return false; } } } 

inheritance自ProtectedProperty:

 public class ProtectedProperty { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int PropertyId { get; set; } [Required] public string SubId { get; set; } public int Downloads { get; set; } [Required] public UserProfile Owner { get; set; } [Required] public string Name { get; set; } [Required] public ProtectedPropertyType Type { get; set; } } 

最后UserProfile:

  [Table("UserProfile")] public class UserProfile { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int UserId { get; set; } [Required] public string UserName { get; set; } [Required] public string AffiliateId { get; set; } public UserProfile Referer { get; set; } [Required] public int Balance { get; private set; } [Required] [EmailAddress] public string PaypalEmail { get; set; } public int AllTimeEarnings { get; set; } } 

我认为问题是密码上的UserProfile对象没有附加到您用于插入的DbContext。 这使得EF认为它是一个新对象。

尝试:

 using (MediaProfitsDb db = new MediaProfitsDb()) { db.UserProfiles.Attach(pw.UserProfile); db.ProtectedPasswords.Add(pw); db.SaveChanges(); return true; }