【发布时间】:2019-11-17 07:00:39
【问题描述】:
使用
.NET Core SDK(反映任何 global.json): 版本:2.2.300 提交:73efd5bd87
和
休眠 5.2.5
拥有以下实体
public class Customer : Entity {
public Customer() {
Initialize();
}
public virtual string Name { get; set; }
public virtual string LegalName { get; set; }
public virtual string VATCode { get; set; }
public virtual ICollection<Site> Sites { get; set; }
public virtual DateTime Created { get; set; } = DateTime.UtcNow;
private void Initialize() {
Sites = new List<Site>();
}
}
public class Site : Entity {
public virtual string Address { get; set; }
public virtual string City { get; set; }
public virtual string Country { get; set; }
public virtual Customer Customer { get; set; }
}
使用以下映射器
internal class CustomerConfiguration : ClassMapping<Customer> {
public CustomerConfiguration() {
Table( TableNames.CustomersTable );
Id( x => x.EntityID, im => {
im.Column( "CustomerID" );
im.Generator( Generators.Identity );
} );
[... code omitted for brevity ...]
Set<Site>( property => property.Sites,
collection => {
collection.Fetch( CollectionFetchMode.Join );
collection.Lazy( CollectionLazy.Lazy );
collection.Cascade( Cascade.Persist.Include( Cascade.DeleteOrphans ) );
collection.Inverse( true );
collection.Key( keyMapping => {
keyMapping.Column( "CustomerID" );
} );
},
mapping => {
mapping.OneToMany( relationalMapping => {
relationalMapping.Class( typeof( Site ) );
} );
} );
}
}
internal class SiteConfiguration : ClassMapping<Site> {
public SiteConfiguration() {
Table( TableNames.SitesTable );
Id( x => x.EntityID, im => {
im.Column( "SiteID" );
im.Generator( Generators.Identity );
} );
[... code omitted for brevity ...]
ManyToOne( x => x.Customer, mm => {
mm.Column( "CustomerID" );
mm.NotNullable( true );
} );
}
}
我猜这个映射不正确,因为如果我做类似的事情
using ( var session = sessionFactory.OpenSession() ) {
var customer = new Customer() {
Name = $"Customer 1",
LegalName = $"Customer 1 LLC",
VATCode = "xxxxxxxxx",
Created = DateTime.UtcNow
};
customer.Sites.Add( new Site() {
Address = $"Address Customer 1",
City = $"City Customer 1",
Country = $"Country Customer 1",
Customer = customer
} );
session.Save( customer );
}
我得到以下异常
未处理的异常:NHibernate.TransientObjectException:对象引用了未保存的瞬态实例 - 在刷新之前保存瞬态实例或将属性的级联操作设置为使其自动保存的内容。类型:Nhibernate.ConsoleApp.Entities.Site,实体:[Site 0]
有什么建议吗?
编辑
实际上问题出在不同的区域。这是因为存在两个已注册的侦听器(IDeleteEventListener 和 IUpdateEventListener)。每当我添加这些更新和删除都不起作用。但是,感谢Roman Artiukhin 评论,我能够发现问题
【问题讨论】:
-
@Alexander 我确实阅读了所有引用的帖子,但除非我没有得到区别,否则就我而言,没有复合 ID。两个表都使用代理键作为数据库标识列。我已更新问题以添加映射 ID。能详细点吗?
标签: asp.net-core nhibernate nhibernate-mapping asp.net-core-2.2