EF代码优先中的关系问题 [英] relationship problems in EF code-first

查看:68
本文介绍了EF代码优先中的关系问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个要加入游戏和详细信息的表。游戏有一个详细信息

I have two tables that i want to join Game and Details. Game has one Detail

问题是我无法正确绑定表格。我得到的错误是

The problem is that i cant bind the tables correct. The error i get is

实体类型'Game'和'Details'无法共享表'Details,因为它们不在同一类型层次结构中或没有有效的一对一外键关系,并且它们之间具有匹配的主键。

"The entity types 'Game' and 'Details' cannot share table 'Details' because they are not in the same type hierarchy or do not have a valid one to one foreign key relationship with matching primary keys between them."

这是我的实现方式

public class Game
{
    [Key]
    [ForeignKey("GameDetails")]
    public int GameId { get; set; }

    public string GameName { get; set; }

    //Navigation prop
    public virtual Details GameDetails { get; set; }
    public virtual ICollection<Details> DetailsId { get; set; }
}

public class Details
{
    [Key]
    public int DetailsId { get; set; }

    public int GameId { get; set; }
    public int RatingId { get; set; }

    public int Grade { get; set; }

    //Navigation prop
    [ForeignKey("DetailsId")]
    public virtual Game GameDetails { get; set; }
    public virtual RatingCompany RatingCompany { get; set; }
}

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Game>().HasKey(f => f.GameId);
        modelBuilder.Entity<Game>()
            .Map(m =>
                     {
                         m.Properties(b => new {b.GameId});
                         m.ToTable("Details");
                     });
    }

我如何以1-1关系正确绑定它?

How can i bind it correctly with a 1-1 relationship?

推荐答案

如果覆盖OnModelCreating,则不应具有属性属性。

If you override OnModelCreating you shouldn't have the property attributes.

这篇关于EF代码优先中的关系问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆