简体   繁体   English

实体框架子实体的唯一属性

[英]Entity framework unique property of child entity

I use model similar to popular Blog/Post EntityFramework examples: 我使用类似于流行的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; } 
}

I need to have Post.Title to be unique per Blog. 我需要有Post.Title,才能使每个Blog唯一。 For now, I have 现在,我有

protected override DbEntityValidationResult ValidateEntity

Here I need to implement logic to check for duplicates, which is not obvious because I need to check Posts.Local and Posts in DB, also logic depends on entityEntry.Status. 在这里,我需要实现检查重复项的逻辑,这并不是很明显,因为我需要检查Posts.Local和DB中的Posts,逻辑也依赖于entityEntry.Status。 Is this the only possible way to implement this restriction or maybe some more elegant solution exists? 这是实施此限制的唯一可能方法,还是存在一些更优雅的解决方案?

How about adding a unique index on them: 如何在它们上添加唯一索引:

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM