如何在MySQL表之间建立关系

时间:2018-08-01 18:40:26

标签: c# asp.net-mvc

我想在我的MySQL数据库中的3个表之间建立关系。用户可以具有多个品牌->一个品牌可以具有多个CarModel。一个CarModel不能出现在更多品牌中。品牌和汽车模型必须唯一。仅当用户登录时才能添加品牌和汽车模型。我使用了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; }
}

这是我的CarModel

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

有人可以告诉我如何在表格之间建立关系吗?预先感谢!

1 个答案:

答案 0 :(得分:0)

首先,创建集合实体,即品牌。然后在其中引用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; }
}
}