2

私の問題は、次のコードが 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;
            }
        }
}

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; }
}
4

1 に答える 1

2

問題は、パスワードの UserProfile オブジェクトが、挿入に使用している DbContext に関連付けられていないことだと思います。これにより、EF はそれが新しいオブジェクトであると考えます。

試す:

using (MediaProfitsDb db = new MediaProfitsDb())
{
    db.UserProfiles.Attach(pw.UserProfile);
    db.ProtectedPasswords.Add(pw);
    db.SaveChanges();
    return true;
}
于 2013-06-30T17:23:20.620 に答える