[英]EntityFramework, Database design Table with nullable foreign keys
So I have this issue with my database design. 因此,我的数据库设计存在这个问题。 I have four tables: Garments , Attachments , Images and Fonts .
我有四个表: Garments , Attachments , Images和Fonts 。
A Garment can have multiple or no Attachments so that is easy to map: 服装可以有多个附件 ,也可以没有附件,因此很容易映射:
modelBuilder.Entity<Garment>().HasMany(m => m.Attachments).WithOptional().HasForeignKey(m => m.GarmentId);
But the complication arrises with Attachments . 但是并发症伴随着附件 。 I have read that having multiple nullable foreign keys is bad practice, but I can't work out how to map this flow.
我已经读到有多个可为空的外键是不好的做法,但是我不知道如何映射此流。
An Attachement can either have an Image OR a Font . 附件可以具有图像或字体 。 It can never have both and must have at least one.
它永远不能同时拥有,至少必须拥有一个。
My initial class looked like this: 我的第一堂课是这样的:
public class Attachment
{
public int ImageId { get; set; }
public int FontId { get; set; }
[Required] public int GarmentId { get; set; }
[MaxLength(50)] [Required] public string PanelId { get; set; }
public Image Image { get; set; }
public Font Font { get; set; }
}
but this doesn't enforce anything. 但这并没有执行任何操作。 Is there anyway way that EF can handle this in a good way?
无论如何,EF可以很好地处理此问题吗?
You can use Entity Framework Validation and especially IValidatableObject
您可以使用实体框架验证 ,尤其是
IValidatableObject
public class Attachment : IValidatableObject
{
//...
public Image Image { get; set; }
public Font Font { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Image == null && Font == null)
{
yield return new ValidationResult
("Image or Font must be specified", new[] { "Image", "Font" });
}
if (Image != null && Font != null)
{
yield return new ValidationResult
("You cannot provide both an Image and a Font", new[] { "Image", "Font" });
}
}
}
If you really need it and support is provided, you may add a constraint on the data store. 如果确实需要它并且提供了支持,则可以在数据存储上添加约束。 For SQL Server, see CHECK CONSTRAINT .
对于SQL Server,请参阅CHECK CONSTRAINT 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.