EF Code First ASP.NET C# Design
本文关键字:Design NET ASP Code First EF | 更新日期: 2023-09-27 17:54:56
我正在尝试使用EF Code首先创建一个数据库,但我不确定如何为以下关系定义类,以便它是有效的。
我们有一个User和User有朋友,这反过来又是User的集合,所以我在考虑下面的POCO类
`//Class User
public class User
{
public Guid UserId{get;set;}
public string UserName{get;set;}
public String UserAddress{get;set;}
// other user properties
}
//Class Friend
public class Friend
{
public Guid FriendId{get;set;} //unique identifier for Friend Table
public virtual User CurrentUser{get;set;}
public List<User> lstUserFriends {get;set;} //contains list of all friends that the user has
}`
这看起来性能不错吗?或者你认为你可以建议一个替代方案?
为什么不直接做呢
public class User
{
public Guid UserId{get;set;}
public string UserName{get;set;}
public String UserAddress{get;set;}
public IList<User> Friends{get;set;}
// other user properties
}
需要自引用多对多关系,因为用户可以有多个好友,也可以是多个用户的好友。
public class User
{
public Guid UserId { get; set; }
public string UserName { get; set; }
public String UserAddress { get; set; }
[InverseProperty("Friends")]
public virtual ICollection<User> FriendWith { get; set; }
[InverseProperty("FriendWith")]
public virtual ICollection<User> Friends { get; set;}
}
或者省略InverseProperty
数据注释,使用流畅映射:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasMany(u => u.Friends)
.WithMany(f => f.FriendWith);
// I'm not sure but you can also need to add this:
// .WillCascadeOnDelete(false);
}