EF 4.2 Code First,如何使用Fluent API进行映射?
(因为我有一个预定义的数据库,所以我不能让 EF 重新创建它)。
这是我现在使用的映射(可以工作,但我想使用 Fluent API 重写):
public class League
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid LeagueId { get; set; }
....
#region References
public virtual ICollection<News> News { get; set; }
#endregion
}
public class News
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid NewsId { get; set; }
public Guid LeagueId { get; set; }
....
#region References
[ForeignKey("LeagueId")]
public virtual League League { get; set; }
#endregion
}
现在,我如何使用 Fluent API 映射它?
更新 写了这个并且可以工作,但是有更简单的版本吗?
modelBuilder.Entity<League>().HasMany(x => x.News).WithRequired(y => y.League).HasForeignKey(c => c.LeagueId);
更新2 我添加了课程中缺少的内容。但问题是,如果我就这样尝试,就会失败。我需要在某处指定一个键。我不能让 EF 创建数据库,并且它拒绝只操作表。
(Since i have a database predefined i can't let EF recreate it).
This the mapping i use now (works but i want to rewrite using fluent api):
public class League
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid LeagueId { get; set; }
....
#region References
public virtual ICollection<News> News { get; set; }
#endregion
}
public class News
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid NewsId { get; set; }
public Guid LeagueId { get; set; }
....
#region References
[ForeignKey("LeagueId")]
public virtual League League { get; set; }
#endregion
}
Now, how can i map this using the fluent API?
Update
Wrote this and it works, but is there a simpler version?
modelBuilder.Entity<League>().HasMany(x => x.News).WithRequired(y => y.League).HasForeignKey(c => c.LeagueId);
Update 2
I added those missing from the classes. But the problem is that if i leave it at that and try it, it fails. I need to specify a key somewhere.I can't let EF create the database and it refuses to just operate with tables.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
例如,您应该查看这篇文章: http://www.codeproject.com/Articles/184133/Using-Entity-Framework-4-1-Code-First-with-an-exis
基本部分是,您应该删除默认的数据库初始值设定项:
这应该防止 EF 尝试更改您的数据库或引发错误。它只会尝试根据您提供的内容进行工作。
You should look at this article for example: http://www.codeproject.com/Articles/184133/Using-Entity-Framework-4-1-Code-First-with-an-exis
The base part, is that you should remove default db initializer:
And this should prevent EF from trying to change your db or throw errors. It will just try to work with what you give it.