简体   繁体   中英

Entity framework unique property of child entity

I use model similar to popular Blog/Post EntityFramework examples:

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. 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. 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; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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