2017-01-10 177 views
0

我有這個設置的類別:實體框架1〜1/1 *

public class User 
{ 
    public int Id { get; set; } 
    public string LoginName { get; set; } 
    public int CurrentPasswordId { get; set; } 
    public virtual ArchivedPassword CurrentPassword {get;set;} 
    public virtual ICollection<ArchivedPassword> UsedPasswords { get; set; } 
} 
public class ArchivedPassword 
{ 
    public int Id { get; set; } 

    public string Hash { get; set; } 

    public int UserId { get; set; } 

    public virtual User User { get; set; } 

    public virtual ICollection<User> Users { get; set; } 
} 
ModelBuilder.Entity<ArchivedPassword>() 
    .HasMany(e => e.Users) 
    .WithRequired(e => e.CurrentPassword) 
    .HasForeignKey(e => e.CurrentPasswordId) 
    .WillCascadeOnDelete(false); 

ModelBuilder.Entity<User>() 
    .HasMany(e => e.UsedPasswords) 
    .WithRequired(e => e.User) 
    .HasForeignKey(e => e.UserId) 
    .WillCascadeOnDelete(false); 

當我嘗試添加一個用戶和密碼,EF不容找出更新順序。 這是一個映射問題嗎?

回答

0

我不是專家數據庫。但我認爲你不能讓你能成功,你想爲下面的代碼有什麼相同tables.But兩個不同的外鍵

public class UserContext : DbContext 
{ 
    public DbSet<User> Users { get; set; } 
    public DbSet<Password> Paswords { get; set; } 

} 
public class User 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 

    [NotMapped] 
    public Password Password 
    { 
     get 
     { 
      return Passwords.ElementAt(Passwords.Count - 1); 
     } 
    } 

    public virtual ICollection<Password> Passwords { get; set; } 
} 

public class Password 
{ 
    public int Id { get; set; } 

    public string Hash { get; set; } 

    public virtual User User { get; set; } 
}