我想爲我的社交網絡學校項目做一個數據庫模型。我正在使用實體框架6.問題是我應該如何建模我的Friendship
和Chat
實體。C#實體框架 - 社交網絡 - 友誼,聊天實體
我得到這個錯誤:
Unhandled Exception:
System.Data.Entity.ModelConfiguration.ModelValidationException: One or more validation errors were detected during model generation:Friendship_Chat_Source: : Multiplicity is not valid in Role 'Friendship_Chat_Source' in relationship 'Friendship_Chat'. Because the dependent role properties are not the key properties, the upper bound of the multiplicity of the dependent role must be '*'.
它有可能是一些與此有關:EF Code-First One-to-one relationship: Multiplicity is not valid in Role * in relationship
我真的不明白我應該怎麼辦在這裏。即使我以某種方式擺脫了這個錯誤(不同的數據庫模型),友誼表中的實體框架創建User_Id列作爲外鍵,我真的不知道它爲什麼會這樣做(我不希望它在那裏)。但我真的覺得我的模型應該看起來像這樣,沒有什麼不同。所以我想弄清楚,我該如何編輯這個模型。但是,如果你有不同的模型想法,我也會很感激。
用戶實體:
public class User
{
public int Id { get; set; }
[Required, MinLength(1), MaxLength(50)]
public string NickName { get; set; }
[Required, MinLength(6), MaxLength(50)]
public string PasswordHash { get; set; }
#region Settings
//true if anyone can see user posts
public Visibility PostVisibilityPreference { get; set; } = Visibility.Visible;
#endregion
#region Navigation properties
public virtual HashSet<Friendship> Friendships { get; set; }
public virtual HashSet<Post> Posts { get; set; }
public virtual HashSet<GroupUser> GroupUsers { get; set; }
public virtual HashSet<Comment> Comments { get; set; }
#endregion
}
友誼實體:
public class Friendship
{
#region Primary keys
public int User1Id { get; set; }
public int User2Id { get; set; }
#endregion
[Required]
public DateTime FriendshipStart { get; set; }
#region Foreign keys
//defined using fluent api in MyDbContext:
//User1Id
//User2Id
//and
[ForeignKey("Chat")]
public int? ChatId { get; set; }
#endregion
#region Navigation properties
public virtual User User1 { get; set; }
public virtual User User2 { get; set; }
public virtual Chat Chat { get; set; }
#endregion
}
隨着MyDbContext這個overrided功能OnModelCreating:
protected override void OnModelCreating(DbModelBuilder builder)
{
builder.Entity<Friendship>()
.HasKey(k => new { k.User1Id, k.User2Id });
builder.Entity<Friendship>()
.HasRequired(u => u.User1)
.WithMany()
.HasForeignKey(u => u.User1Id);
builder.Entity<Friendship>()
.HasRequired(u => u.User2)
.WithMany()
.HasForeignKey(u => u.User2Id)
.WillCascadeOnDelete(false);
}
聊天實體:
public class Chat
{
public int Id { get; set; }
#region Foreign keys
public int? FriendshipUser1Id { get; set; }
public int? FriendshipUser2Id { get; set; }
#endregion
#region Navigation properties
public virtual HashSet<Message> Messagges { get; set; }
[ForeignKey("FriendshipUser1Id, FriendshipUser2Id")]
public virtual Friendship Friendship { get; set; }
#endregion
}
我從字面上使它像這個人建議: https://stackoverflow.com/questions/13896503/how-should-i-model-friendships-between-users-with-ef-code-first –
這不是主要問題。我得到的錯誤是友誼和聊天實體之間。順便說一句。我嘗試使用.WithRequired ...()方法,就像你上面寫的那樣,但是它們不能像那樣工作。它不給我u => u.User2選項(而不是intellisense給我u => u。[User類的任何屬性]。我也不想使用複合主鍵。 –