问题
I have following domain classes:
public class News: EntityBase
{
public virtual DateTime CreationDate { get; set; }
public virtual IList<DomainNameToNews> DomainNameToNews { get; set; }
public News()
{
DomainNameToNews=new List<DomainNameToNews>();
}
}
public class DomainNameToNews : EntityBase
{
public virtual DomainName DomainName { get; set; }
public virtual News News { get; set; }
}
Mapping:
public class NewsMap : ClassMap<News>
{
public NewsMap()
{
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.CreationDate).Not.Nullable();
HasMany(x => x.DomainNameToNews).Cascade.AllDeleteOrphan();
}
}
public class DomainNameToNewsMap : ClassMap<DomainNameToNews>
{
public DomainNameToNewsMap()
{
Id(x => x.Id).GeneratedBy.Identity();
References(x => x.News).UniqueKey("UQ_DOMAIN_NEWS").Cascade.Delete();
References(x => x.DomainName).UniqueKey("UQ_DOMAIN_NEWS");
}
}
Explanation:
News can be used in different domains so DomainNameToNews is relationship between them. One news can be used by multiple domains.
Problem: What I want is to delete and add DomainToNews objects through News repository.
On update of News Object this object will have a list of DomainNameToNews so When I will update News the row from DomainNameToNews that will not be in this list I want to delete at all from database .Now the row that is not in this List will have Null News ,but I want to delete at all. How I must to map my object to achieve this? If I didn't explain myself enough clear please ask more details. Thnaks!!
回答1:
You need to specify 'inverse' at the one-to-many collection association.
public class NewsMap : ClassMap<News>
{
public NewsMap()
{
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.CreationDate).Not.Nullable();
HasMany(x => x.DomainNameToNews).Inverse.Cascade.AllDeleteOrphan();
}
}
public class DomainNameToNewsMap : ClassMap<DomainNameToNews>
{
public DomainNameToNewsMap()
{
Id(x => x.Id).GeneratedBy.Identity();
References(x => x.News).UniqueKey("UQ_DOMAIN_NEWS");
References(x => x.DomainName).UniqueKey("UQ_DOMAIN_NEWS");
}
}
Explanation on 'inverse' in this blog post
来源:https://stackoverflow.com/questions/22380027/flunet-nhibernate-all-delete-orphan-not-working-like-expected