Code first table 有两个外键,如果另一个有值,一个应该为空
Code first table with two foreign keys one should be null if the other has value
好吧,我正在尝试对我的 table 应用检查约束!所以我有国家代表,每个国家都应该有一名代表 Individual
或 Organization
但不能同时有;
例如,如果 Individual
代表国家,则 OrganizationId
应该是 null
。
我如何使用 Code First 数据注释应用此检查约束,或者是否有任何其他方式。
这是我的代码:
class CountryRepresentative
{
[Column(Order = 0), Key, ForeignKey("Incident")]
public Guid CountryId { get; set; }
[Column(Order = 1), ForeignKey("Organization")]
public int OrganizationId { get; set; }
[Column(Order = 2), ForeignKey("Individual")]
public int IndividualId { get; set; }
public virtual Organization Organization { get; set; }
public virtual Individual Individual { get; set; }
public virtual Incident Incident { get; set; }
}
我希望一切都清楚。
谢谢小伙伴们
我会使用 Fluent API 手动定义约束:
migrationBuilder.Sql("ADD CONSTRAINT CK_ONLY_ONE_VAL CHECK
((nullif(one,'') is null or nullif(other,'') is null)
and not (nullif(one,'') is null and nullif(other,'') is null) );");
nullif()
将有助于检查空值并转换为 null
...
好吧,我正在尝试对我的 table 应用检查约束!所以我有国家代表,每个国家都应该有一名代表 Individual
或 Organization
但不能同时有;
例如,如果 Individual
代表国家,则 OrganizationId
应该是 null
。
我如何使用 Code First 数据注释应用此检查约束,或者是否有任何其他方式。
这是我的代码:
class CountryRepresentative
{
[Column(Order = 0), Key, ForeignKey("Incident")]
public Guid CountryId { get; set; }
[Column(Order = 1), ForeignKey("Organization")]
public int OrganizationId { get; set; }
[Column(Order = 2), ForeignKey("Individual")]
public int IndividualId { get; set; }
public virtual Organization Organization { get; set; }
public virtual Individual Individual { get; set; }
public virtual Incident Incident { get; set; }
}
我希望一切都清楚。 谢谢小伙伴们
我会使用 Fluent API 手动定义约束:
migrationBuilder.Sql("ADD CONSTRAINT CK_ONLY_ONE_VAL CHECK
((nullif(one,'') is null or nullif(other,'') is null)
and not (nullif(one,'') is null and nullif(other,'') is null) );");
nullif()
将有助于检查空值并转换为 null
...