实体框架 - 许多? [英] Entity Framework - Many to many?

查看:99
本文介绍了实体框架 - 许多?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义一个多对多关系如下:

I'm defining a many-to-many relationship as follows:

    modelBuilder.Entity<GameSessionEntry>().
         HasMany(c => c.Users).
         WithMany(p => p.GameSessionEntries).
         Map(
          m =>
          {
              m.MapLeftKey("SessionId");
              m.MapRightKey("UserId");
              m.ToTable("UserSessions");
          });

表'UserSessions'上的外键与列'UserId'可能不能创建
,因为主键列不能是
确定。使用AddForeignKey fluent API完全指定
外键。

The Foreign Key on table 'UserSessions' with columns 'UserId' could not be created because the principal key columns could not be determined. Use the AddForeignKey fluent API to fully specify the Foreign Key.

我是数据库工作的新用户,EntityFramework

I'm new to database work and the EntityFramework in general - what is it asking me to do?

推荐答案

这是我通常去创建一个多对多的表这不需要流畅的api配置)

This is how I usually go about creating a many to many table (note this requires no fluent api configuration)

public class User
{
    public int Id { get; set; }
    public virtual ICollection<UserSession> UserSessions { get; set; }
}

public class Session
{
    public int Id { get; set; }
    public virtual ICollection<UserSession> UserSessions { get; set; }
}

public class UserSession
{
    [Key]
    [Column(Order = 1)]
    public int UserId { get; set; }

    [Key]
    [Column(Order = 2)]
    public int SessionId{ get; set; }

    public virtual User User { get; set; }
    public virtual Session Session { get; set; }
}

这篇关于实体框架 - 许多?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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