使用Entity Framework实现标记功能

时间:2013-12-06 19:38:46

标签: c# entity-framework

我希望能够以最简单的方式标记任何实体。我有2个实体(书籍和作者)

public class Book : AbstractTag
{
    [Key]
    public int BookId { get; set; }
    public string Title { get; set; }
    public string Genre { get; set; }

    public Author Author { get; set; }
}

public class Author : AbstractTag
{
    [Key]
    public int AuthorId { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }

    public virtual ICollection<Book> Books { get; set; }
}

他们都继承自AbstractTag

public class AbstractTag : ITaggable
{
    public AbstractTag()
    {
        Tags = new List<Tag>();
    }

    public virtual ICollection<Tag> Tags { get; set; }
}

可以标记。我不想要重复的标签。

这是我的标签实体:

public class Tag
{
    public Tag()
    {
        Books = new List<Book>();
        Authors = new List<Author>();
    }

    [Key]
    public int TagId { get; set; }

    public string Label { get; set; }

    public virtual ICollection<Book> Books { get; set; }
    public virtual ICollection<Author> Authors { get; set; }
}

public interface ITaggable
{
    ICollection<Tag> Tags { get; set; }
}

以下是我用来将标记附加到实体的代码:

public interface ITagService
{
    TEntity Tag<TEntity>(TEntity entity, string str) where TEntity : ITaggable;
    TEntity Untag<TEntity>(TEntity entity, string str) where TEntity : ITaggable;
}

public class TagService : ITagService
{
    private readonly Context _context = new Context();

    public TagService()
    {
    }

    public TagService(Context context)
    {
        _context = context;
    }

    public TEntity Tag<TEntity>(TEntity entity, string str) where TEntity : ITaggable
    {
        string tag = str.Trim();

        if (entity.Tags.All(t => t.Label != tag))
        {
            Tag t = _context.Tags.Add(new Tag {Label = tag});
            entity.Tags.Add(t);
        }

        return entity;
    }

    public TEntity Untag<TEntity>(TEntity entity, string str) where TEntity : ITaggable
    {
        Tag tag = entity.Tags.FirstOrDefault(x => x.Label == str);

        if (tag != null)
            entity.Tags.Remove(tag);

        return entity;
    }
}

我遇到的问题是,它会产生重复,我不明白为什么因为数据库表是生成的。显然我的代码是错的,但我无法弄清楚为什么和在哪里。

var context = new Context();

        var author = new Author {FirstName = "Stephen", LastName = "King"};
        var book = context.Books.Add(new Book
            {
                Title = "Title",
                Author = author,
                Genre = "Sci-Fi"
            });

        var service = new TagService(context);
        service.Tag(book, "best");
        service.Tag(author, "best");

        context.SaveChanges();

因此,当我执行该代码时,我只想要一个应该是“最佳”的标签。相反,我有2个标签,都是“最好的”。任何人都可以解释原因,我该如何解决这个问题

更新 以下是EF生成的内容:

public override void Up()
    {
        CreateTable(
            "dbo.Books",
            c => new
                {
                    BookId = c.Int(nullable: false, identity: true),
                    Title = c.String(),
                    Genre = c.String(),
                    Author_AuthorId = c.Int(),
                })
            .PrimaryKey(t => t.BookId)
            .ForeignKey("dbo.Authors", t => t.Author_AuthorId)
            .Index(t => t.Author_AuthorId);

        CreateTable(
            "dbo.Authors",
            c => new
                {
                    AuthorId = c.Int(nullable: false, identity: true),
                    FirstName = c.String(),
                    LastName = c.String(),
                })
            .PrimaryKey(t => t.AuthorId);

        CreateTable(
            "dbo.Tags",
            c => new
                {
                    TagId = c.Int(nullable: false, identity: true),
                    Label = c.String(),
                })
            .PrimaryKey(t => t.TagId);

        CreateTable(
            "dbo.TagBooks",
            c => new
                {
                    Tag_TagId = c.Int(nullable: false),
                    Book_BookId = c.Int(nullable: false),
                })
            .PrimaryKey(t => new { t.Tag_TagId, t.Book_BookId })
            .ForeignKey("dbo.Tags", t => t.Tag_TagId, cascadeDelete: true)
            .ForeignKey("dbo.Books", t => t.Book_BookId, cascadeDelete: true)
            .Index(t => t.Tag_TagId)
            .Index(t => t.Book_BookId);

        CreateTable(
            "dbo.TagAuthors",
            c => new
                {
                    Tag_TagId = c.Int(nullable: false),
                    Author_AuthorId = c.Int(nullable: false),
                })
            .PrimaryKey(t => new { t.Tag_TagId, t.Author_AuthorId })
            .ForeignKey("dbo.Tags", t => t.Tag_TagId, cascadeDelete: true)
            .ForeignKey("dbo.Authors", t => t.Author_AuthorId, cascadeDelete: true)
            .Index(t => t.Tag_TagId)
            .Index(t => t.Author_AuthorId);

    }

    public override void Down()
    {
        DropIndex("dbo.TagAuthors", new[] { "Author_AuthorId" });
        DropIndex("dbo.TagAuthors", new[] { "Tag_TagId" });
        DropIndex("dbo.TagBooks", new[] { "Book_BookId" });
        DropIndex("dbo.TagBooks", new[] { "Tag_TagId" });
        DropIndex("dbo.Books", new[] { "Author_AuthorId" });
        DropForeignKey("dbo.TagAuthors", "Author_AuthorId", "dbo.Authors");
        DropForeignKey("dbo.TagAuthors", "Tag_TagId", "dbo.Tags");
        DropForeignKey("dbo.TagBooks", "Book_BookId", "dbo.Books");
        DropForeignKey("dbo.TagBooks", "Tag_TagId", "dbo.Tags");
        DropForeignKey("dbo.Books", "Author_AuthorId", "dbo.Authors");
        DropTable("dbo.TagAuthors");
        DropTable("dbo.TagBooks");
        DropTable("dbo.Tags");
        DropTable("dbo.Authors");
        DropTable("dbo.Books");
    }

1 个答案:

答案 0 :(得分:0)

您不使用相同的Tag实体,只使用标记内容。在Tag方法中,您始终创建具有新TagId的新实体。如果标签存在并且使用该实体而不是创建新实体,则必须使用给定标签添加额外检查。例如:

if (entity.Tags.All(t => t.Label != tag))
{
    var tagEntity = _context.Tags.FirstOrDefault(t => t.Label == tag);

    if(tagEntity == null)
        tagEntity = _context.Tags.Add(new Tag {Label = tag});
    entity.Tags.Add(tagEntity);
}