【问题标题】:Entity Framework code first join 3 tablesEntity Framework代码先加入3个表
【发布时间】:2018-12-29 19:50:29
【问题描述】:

我有 3 节课:

public class ApplicationUser : IdentityUser
{
    // all the default ApplicationUser properties etc...
    public virtual ICollection<UserShips> UserShips { get; set; }
    // other properties ...
}

public class Ship
{
    public int ShipId {get; set;}
    public virtual ICollection<UserShips> UserShips { get; set; }
    // other ship properties
}

这个ship表已经有数据插入到表中,这些数据是静态的,不能被只有访问的用户更改

public class UserShips 
{
    public int UserShipId {get; set;}
    public int ShipId {get; set;}
    public string Id {get; set;}
    public virtual ApplicationUser ApplicationUser {get; set;}
    public virtual Ship Ship {get; set;}
}

这就是我目前所拥有的,我已经使用 Fluent API 尝试了几种不同的实体映射,但均未成功。

我想要实现的是:每个用户可以有多个用户身份,每个用户身份可以有一个 shipid(基于数据库中的条目)和一个用户 ID,任何人都可以帮助我解决我的困境吗?非常乐意发布您需要的更多信息!

【问题讨论】:

    标签: c# entity-framework asp.net-mvc-5 ef-code-first ef-code-first-mapping


    【解决方案1】:

    如果您愿意使用 DataAnnotations,您可以尝试一下(您在帖子中从未提到过必须使用 Fluent Mappings 的解决方案)。

    [Table("user")]
    public class User
    {
    [Key,Column("id")]
    public string Id {get; set;
    [ForeignKey(nameof(Id))]
    public virtual ICollection<UserShips> UserShips { get; set; }
    // other properties ...
    }
    
    [Table("ship")]
    public class Ship
    {
    [Key, Column("shipid")]
    public int ShipId {get; set;}
    [ForeignKey(nameof(ShipId))]
    public virtual ICollection<UserShips> UserShips { get; set; }
    // other ship properties
    }
    
    [Table("userships")]
    public class UserShips 
    {
    [Key,Column("usershipid")]
    public int UserShipId {get; set;}
    [Column("shipid")]
    public int ShipId {get; set;}
    [Column("id")]
    public string Id {get; set;}
    [ForeignKey(nameof(Id))]
    public virtual User User {get; set;}
    [ForeignKey(nameof(ShipId))]
    public virtual Ship Ship {get; set;}
    }
    

    【讨论】:

    • 感谢您的回复!,我尝试了您的代码但没有成功,我在向 ApplicationUser 类添加数据注释时遇到错误,代表我的错误,因为我提供的上述代码是错误的首先,任何进一步的帮助将不胜感激
    猜你喜欢
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-05
    • 2012-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多