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; }
- 三个System.Drawing方法表现出慢速绘制或闪烁:解决方案? 或其他选择?
- 在DateTime-range上使用ContentSearch-API查询Sitecore Lucene-index
- 在ASP.NET MVC5上设置值之后,静态属性在每个请求中始终为null
- System.Delegate System.Reflection.MethodInfo.CreateDelegate(System.Type)
- MVC 3尝试将URL启动到View而不是控制器操作
- 在策略设计模式的情况下,Hangfire服务器无法选择作业
- asp.net mvc应用程序中的工作单元模式
- 如何在n层体系结构中将entity framework模型类与Business Layer类映射 – ASP.NET-MVC
- 如何在MVC 4中的同一视图中打开窗口?
- Sitecore – ControllerRendering抱怨控制器“未找到或未实现IController”。
- 嵌套查询MVC LINQ