首页 > 解决方案 > 如何在 MySQL 表之间建立关系

问题描述

我想在我的 MySQL 数据库中的 3 个表之间建立关系。用户可以拥有多个品牌 -> 一个品牌可以拥有多个 CarModel。一个 CarModel 不能出现在多个品牌中。Brands 和 CarModels 必须是唯一的。只有在用户登录后才能添加品牌和车型。我使用了 ASP .NET Core UserIdentity。

这是我的品牌模型:

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 class CarModel
{
    [Key]
    public int Id { get; set; }

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

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

这是我的 ApplicationDbContext

 public virtual DbSet<Brand> Brands { get; set; }

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

有人可以告诉我如何建立表格之间的关系吗?提前致谢!

标签: c#asp.net-mvc

解决方案


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

相互声明具有导航属性的两个类。ForeignKey用其主键上的属性标记其中一个表(从属表) 。EF 从中推断出一对多:

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; }
}
}

推荐阅读