[英]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.