[英]Entity framework unique property of child entity
我使用类似于流行的Blog / Post EntityFramework示例的模型:
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
public virtual List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public virtual Blog Blog { get; set; }
}
我需要有Post.Title,才能使每个Blog唯一。 现在,我有
protected override DbEntityValidationResult ValidateEntity
在这里,我需要实现检查重复项的逻辑,这并不是很明显,因为我需要检查Posts.Local和DB中的Posts,逻辑也依赖于entityEntry.Status。 这是实施此限制的唯一可能方法,还是存在一些更优雅的解决方案?
如何在它们上添加唯一索引:
[Index("IdAndTitle", 1, IsUnique = true)]
public string Title { get; set; }
[Index("IdAndTitle", 2]
public int BlogId { get; set; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.