我想在我的应用程序中实现聊天,我创建的数据库模式为:
当我首先使用Entity Framework数据库生成模型时,我得到了:
我不想拥有User,User1,而是想保留From和To,当我直接在模型中更改它们时,由于数据库和模型不相同,我出现了错误-我该如何处理这个吗?
答案 0 :(得分:0)
如果您不喜欢Entity Framework为您选择的表和列的默认名称,则可以告诉Entity Framework它们应该是什么。
您可以为此使用属性。恕我直言,这会使您的代码看起来很恐怖。除此之外,您不能在具有不同名称的表和列的其他数据库中使用类。
因此,我更喜欢在DbContext.OnModelCreating
中使用流利的API
让我们首先定义类User和Message
class User
{
public int Id {get; set;}
... // other properties
// every User has zero or more "From" messages (one-to-many)
public virtual ICollection<Message> FromMessages {get; set;}
// every user has zero or more "To" message (one-to-many)
public virtual ICollection<Message> ToMessages {get; set;}
}
class Message
{
public int Id {get; set;}
... // other properties
// every Message has exactly one "From" user using foreign key FromUserId
public int FromUserId {get; set;}
public virtual User From {get; set;}
// every Message has exactly one "To" user using foreign key ToUserId
public int ToUserId {get; set;}
public virtual User To {get; set;}
}
在Entity Framework中,表的列由非虚拟属性表示;虚拟属性表示表之间的关系。
因此,外键不是虚拟的,外键指向的项目是虚拟的。
使用流畅的API的时间:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
var messageEntity = modelBuilder.Entity<Message>();
// every messages belongs to exactly one User using foreign key `FromUserId`
// every such User has zero or more From messages
messageEntity.HasRequired(message => message.From)
.WithMany(user => user.FromMessages)
.HasForeignKey(message => message.FromUserId)
// the same for To, using ToUserId:
messageEntity.HasRequired(message => message.To)
.WithMany(user => user.ToMessages)
.HasForeignKey(message => message.ToUserId);
}
您还可以从Users(用户)开始以相反的方式进行操作:
var userEntity = modelBuilder.Entity<User>();
// every user has zero or more FromMessages (one-to-many)
userEntity.HasMany(user => user.FromMessages)
.WithRequired(message => message.From)
.HasForeignKey(message => message.FromUserId);
// every user has zero or more ToMessages (one-to-many)
userEntity.HasMany(user => user.ToMessages)
.WithRequired(message => message.To)
.HasForeignKey(message => message.ToUserId);