开发者

NHibernate - Saving simple parent-child relationship generates unnecessary selects with assigned id

开发者 https://www.devze.com 2023-01-01 16:46 出处:网络
Entities: public class Parent { virtual public long Id { get; set; } virtual public string Description { get; set; }

Entities:

public class Parent
{
    virtual public long Id { get; set; }
    virtual public string Description { get; set; }

    virtual public ICollection<Child> Children { get; set; }
}

public class Child
{
    virtual public long Id { get; set; }
    virtual public string Description { get; set; }

    virtual public Parent Parent { get; set; }
}

Mappings:

public class ParentMap : ClassMap<Parent>
{
    public ParentMap()
    {
        Id(x => x.Id).GeneratedBy.Assigned();

        Map(x => x.Description);

        HasMany(x => x.Children)
            .AsSet()
            .Inverse()
            .Cascade.AllDeleteOrphan();
    }
}

public class ChildMap : ClassMap<Child>
{
    public ChildMap()
    {
        Id(x => x.Id).GeneratedBy.Assigned();

        Map(x => x.Description);

        References(x => x.Parent)
            .Not.Nullable()
            .Cascade.All();
    }
}

and

        using (var session = sessionFactory.OpenSession())
        using (var transaction = session.BeginTransaction())
        {
            var parent = new Parent { Id = 1 };

            parent.Children = new HashSet<Child>();

            var child1 = new Child { Id = 2, Parent = parent };
            var child2 = new Child { Id = 3, Parent = parent };

            parent.Children.Add(child1);
            parent.Children.Add(child2);

            session.Save(parent);

            transaction.Commit();
        }

this codes generates following sql

NHibernate: SELECT child_.Id, child_.Description as Descript2_0_, child_.Parent_id as Parent3_0_ FROM [Child] child_ WHERE child_.Id=@p0;@p0 = 2 [Type: Int64 (0)]
NHibernate: SELECT child_.Id, child_.Description as Descript2_0_, child_.Parent_id as Parent3_0_ FROM [Child] child_ WHERE child_.Id=@p0;@p0 = 3 [Type: Int64 (0)]
NHibernate: INSERT INTO [Parent] (Description, Id) VALUES (@p0, @p1);@p0 = NULL[Type: String (4000)], @p1 = 1 [Type: Int64 (0开发者_运维问答)]
NHibernate: INSERT INTO [Child] (Description, Parent_id, Id) VALUES (@p0, @p1, @p2);@p0 = NULL [Type: String (4000)], @p1 = 1 [Type: Int64 (0)], @p2 = 2 [Type:Int64 (0)]
NHibernate: INSERT INTO [Child] (Description, Parent_id, Id) VALUES (@p0, @p1, @p2);@p0 = NULL [Type: String (4000)], @p1 = 1 [Type: Int64 (0)], @p2 = 3 [Type:Int64 (0)]

Why are these two selects generated and how can I remove it?


The selects are there because you are explicitly setting the Ids. NHibernate doesn't know whether to inser or update so it has to find out if they exist in the database. If they do it will update, if not (as in your case) it will insert.

0

精彩评论

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

关注公众号