c# - 如何在 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; }
有人可以告诉我如何建立表格之间的关系吗?提前致谢!
解决方案
首先,创建集合实体,即品牌。然后在其中引用 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; }
}
}
推荐阅读
- javascript - 渲染函数中出现意外的令牌返回。反应原生
- arrays - 将整数字符串转换为 pyserial 的字节数组
- python - 如何为类指定字符串表示
- docker - 运行在不同端口上的两个服务的 nginx proxy_pass 配置
- bash - bash 变量的值翻倍 - 为什么?
- c# - File.Copy,在 mscorlib.dll 中发生“System.IO.IOException”类型的未处理异常
- python - Where Column item is equal to specific value insert new item
- java - 在为具有虚拟标题的单链表创建迭代器时遇到问题
- php - 外键约束的格式不正确 - Laravel
- php - 获取结果集列中的数字总和