我想在我的MySQL数据库中的3个表之间建立关系。用户可以拥有多个品牌->一个品牌可以拥有多个CarModels。一个CarModel不能出现在多个品牌中。品牌和CarModels必须是唯一的。仅当用户已登录时,才能添加品牌和CarModels。我用的是.NET核心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; }谁能告诉我如何建立这些表之间的关系?提前感谢!
发布于 2018-08-02 03:03:51
首先,创建集合实体,即Brand。然后引用其中的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; }
}
}https://stackoverflow.com/questions/51640226
复制相似问题