首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在MySQL表之间建立关系

如何在MySQL表之间建立关系
EN

Stack Overflow用户
提问于 2018-08-02 02:40:26
回答 1查看 81关注 0票数 0

我想在我的MySQL数据库中的3个表之间建立关系。用户可以拥有多个品牌->一个品牌可以拥有多个CarModels。一个CarModel不能出现在多个品牌中。品牌和CarModels必须是唯一的。仅当用户已登录时,才能添加品牌和CarModels。我用的是.NET核心UserIdentity。

这是我的品牌模型:

代码语言:javascript
复制
public class Brand
{
    [Key]
    public int Id { get; set; }

    [Required]
    [StringLength(50)]
    public string BrandName { get; set; }

    [ForeignKey("Author")]
    public string AuthorId { get; set; }

    public virtual ApplicationUser Author { get; set; }
}

这是我的CarModel

代码语言:javascript
复制
 public class CarModel
{
    [Key]
    public int Id { get; set; }

    [Required]
    [StringLength(50)]
    public string Model { get; set; }

    [ForeignKey("Brand")]
    public string BrandId { get; set; }
}

这是我的ApplicationDbContext

代码语言:javascript
复制
 public virtual DbSet<Brand> Brands { get; set; }

    public virtual DbSet<CarModel> CarModels { get; set; }

谁能告诉我如何建立这些表之间的关系?提前感谢!

EN

Stack Overflow用户

发布于 2018-08-02 03:03:51

首先,创建集合实体,即Brand。然后引用其中的ApplicationUser实体的Id

将带有导航属性的两个类声明为彼此。使用主键上的ForeignKey属性标记其中一个表(依赖表)。EF由此推断出一对多:

代码语言:javascript
复制
public class ApplicationUser : IdentityUser<Guid, GuidUserLogin, GuidUserRole, GuidUserClaim>
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(ApplicationUserManager manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            return userIdentity;
        }

        public ApplicationUser()
        {
           Brands = new Collection<Brand>();
        }

        public ICollection<Brand> Brands { get; set; }
    }

public class Brand
{
    [Key]
    public int Id { get; set; }

    [Required]
    [StringLength(50)]
    public string BrandName { get; set; }

    [ForeignKey("Author")]
    public string AuthorId { get; set; }

    public virtual ApplicationUser Author { get; set; }

    public virtual List<CarModel> CarsModel { get; set; }
}

 public class CarModel
{
    [Key]
    public int Id { get; set; }

    [Required]
    [StringLength(50)]
    public string Model { get; set; }

    [ForeignKey("Brand")]
    public string BrandId { get; set; }
}
}
票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51640226

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档