开发者

FluentNhibernate HasManytoMany Relation - It doesnt add into the link table

开发者 https://www.devze.com 2023-01-19 17:59 出处:网络
Using fluentnhibernate i am having a problem with the link table insertion. Here is my entities public partial class Item

Using fluentnhibernate i am having a problem with the link table insertion.

Here is my entities

public partial class Item
{
    public virtual int Id
    {
        get;
        set;
    }

    public virtual string Description
    {
        get;
      开发者_如何学编程  set;
    }
    public virtual IList<Category> Categories
    {
        get;
        set;
    }
}
public partial class Category
{
    public virtual int Id
    {
        get;
        set;
    }

    public virtual string Name
    {
        get;
        set;
    }
    public virtual string Description
    {
        get;
        set;
    }
    public virtual IList<Item> Items
    {
        get;
        set;
    }
}

Here is my mappings.

public class ItemMapping : ClassMap<Item>
{
    public ItemMapping()
    {
        Table("Item");
        Schema("dbo");
        Id(x => x.Id);
        Map(x => x.Description);
        HasManyToMany(x => x.Categories)
            .ChildKeyColumn("Item_id")
            .ParentKeyColumn("Category_id")
            .Table("CategoriesToItems")
            .AsSet();
        }
}

    public class CategoryMapping : ClassMap<Category>
{
    public CategoryMapping()
    {
        Table("Category");
        Schema("dbo");
        Id(x => x.Id);
        Map(x => x.Description);
        Map(x => x.Name);
        HasManyToMany(x => x.Items)
            .ChildKeyColumn("Category_id")
            .ParentKeyColumn("Item_id")
            .Table("CategoriesToItems")
            .AsSet();
    }
}

Here is how i add it to collection in my mvc page

var category = CategoryTask.Query(x => x.Id == post.Category).FirstOrDefault();

var item = new Item
                {
                    Categories = new List<Category> { category },
                    Tags = tags   
                };
ItemTasks.Save(item);

My question is why it doesnt add the relations in my link table "CategoriesToItems". The table is already in the database with Category_Id (FK, int, not null) and Item_Id (FK, int, not null).

Where is the problem? why it doesnt add it to relation table?


It's hard to say what's really wrong when we can't see what your ItemTasks.Save does under the covers. Are you wrapping your save in a transaction? If not, you should be.


You should call Session.Flush() just before the transaction.Commit() as well.


I am not certain if the problem has been solved, but it looks similar to my problem (fluentnhibernate hasmanytomany same identifier exception).

Also, it looks like your parent and child key columns are backward.

0

精彩评论

暂无评论...
验证码 换一张
取 消