EF 4.2代码优先,如何使用流畅的API进行映射

本文关键字:API 映射 何使用 代码 EF | 更新日期: 2023-09-27 18:16:21

(因为我有一个预定义的数据库,我不能让EF重新创建它)。

这是我现在使用的映射(工作,但我想用流利的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
}

现在,我如何使用流畅的API映射它?

写了这个,它工作,但有没有一个更简单的版本?

modelBuilder.Entity<League>().HasMany(x => x.News).WithRequired(y => y.League).HasForeignKey(c => c.LeagueId);

更新2 我添加了课程中缺失的内容。但问题是,如果我不去尝试它,它就会失败。我需要在某处指定一个键。我不能让EF创建数据库,它拒绝与表操作。

EF 4.2代码优先,如何使用流畅的API进行映射

您应该看看这篇文章:http://www.codeproject.com/Articles/184133/Using-Entity-Framework-4-1-Code-First-with-an-exis基本的部分是,你应该删除默认的数据库初始化器:

Database.SetInitializer<YourContext>(null);

这样可以防止EF试图更改db或抛出错误。