entity-framework - Code first 与约束的一对多关系
问题描述
我有以下由代码首先生成的一对多数据库结构。许多按钮可以添加到一个与单个 GSMUnit 的关系。BtnNo 应该是唯一的(对于每个 GSMUnitId),并且不应重复。目前可以复制。我怎样才能防止这种情况?
public class GSMUnit
{
public int Id { get; set; }
[MaxLength(20)]
public string Model { get; set; }
[MaxLength(40)]
public string GsmName { get; set; }
[MaxLength(40)]
public string TelephoneNum { get; set; }
public int GSMSiteId { get; set; }
public virtual GSMSite GSMSite { get; set; }
public virtual GSMSetting GSMSettings { get; set; }
public virtual ICollection<Button> Buttons { get; set; }
}
public class Button
{
public int Id { get; set; }
[MaxLength(30)]
public string Primary { get; set; }
[MaxLength(30)]
public string Divert1 { get; set; }
[MaxLength(30)]
public string Divert2 { get; set; }
[MaxLength(30)]
public string Divert3 { get; set; }
[MaxLength(20)]
public string AptNo { get; set; }
[MaxLength(10)]
public string Code { get; set; }
[MaxLength(4)]
public string DTO { get; set; }
[MaxLength(4)]
public string Timeband { get; set; }
[MaxLength(15)]
public string BtnNo { get; set; }
[MaxLength(20)]
public string AptName { get; set; }
public int GSMUnitId { get; set; }
public virtual GSMUnit GSMUnit { get; set; }
}
解决方案
您可以Index
为此使用该属性:
public class Button
{
public int Id { get; set; }
[MaxLength(30)]
public string Primary { get; set; }
[MaxLength(30)]
public string Divert1 { get; set; }
[MaxLength(30)]
public string Divert2 { get; set; }
[MaxLength(30)]
public string Divert3 { get; set; }
[MaxLength(20)]
public string AptNo { get; set; }
[MaxLength(10)]
public string Code { get; set; }
[MaxLength(4)]
public string DTO { get; set; }
[MaxLength(4)]
public string Timeband { get; set; }
[MaxLength(15)]
public string BtnNo { get; set; }
[MaxLength(20)]
public string AptName { get; set; }
[Index(IsUnique = true)]
public int GSMUnitId { get; set; }
public virtual GSMUnit GSMUnit { get; set; }
}
但我建议你看看Fluent API。在我看来,它更容易配置。
推荐阅读
- reactjs - 挂载上的 ReactJS 方法
- python-3.x - 如何使 selenium chrome 全屏打开?
- python - 当我在代码中编辑 URL 时,BS4 http 请求出错
- algorithm - 找到最可靠的路径 - Dijkstra 算法
- plot - Makie.jl 中绘图左侧和右侧的双 y 轴
- android - LongClickListerner 没有响应(Kotlin/RecyclerView
- stripe-payments - Stripe 将 paymentIntent 描述传播到 Connected Account 的转账支付
- java - Java判断一个数组是否是另一个数组的子集
- javascript - 数字和句点后第一个数字的正则表达式
- java - tomcat 错误:java.net.BindException:无法分配请求的地址(绑定失败)