Csharp/C#教程:EF每次引用一个时都会创建一个新的UserProfile?分享


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认为它是一个新对象。

尝试:

上述就是C#学习教程:EF每次引用一个时都会创建一个新的UserProfile?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

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

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/990365.html

(0)
上一篇 2021年12月24日
下一篇 2021年12月24日

精彩推荐