EF 4.2 Code First,如何使用Fluent API进行映射?

发布于 2024-12-18 15:58:22 字数 970 浏览 1 评论 0原文

(因为我有一个预定义的数据库,所以我不能让 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

云巢 2024-12-25 15:58:23

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

Database.SetInitializer<YourContext>(null);

这应该防止 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:

Database.SetInitializer<YourContext>(null);

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文