模型中一个属性的多个数据库表 [英] Multiple DB tables for one property in model
问题描述
我有以下课程:
public class Customer {
public virtual int Id {get; set;}
public virtual string Surname {get; set;}
public virtual string Prename {get; set;}
public virtual Location Location {get; set;}
}
public class Location {
public virtual int Id {get; set;}
public virtual string ZipCode {get; set;}
public virtual string Name {get; set;}
}
public class CustomLocation : Location {
}
以及以下映射:
public class CustomerMapping : ClassMapping<Customer> {
public CustomerMapping(){
Table("Customer");
Property(a => a.Surname, b =>
{
b.NotNullable(true);
});
Property(a => a.Prename, b =>
{
b.NotNullable(true);
});
ManyToOne(a => a.Location, b =>
{
b.Column($"FK_Location_Id");
});
}}
public class LocationMapping : ClassMapping<Location> {
public LocationMapping(){
Table("Location");
Property(a => a.ZipCode, b =>
{
b.NotNullable(true);
});
Property(a => a.Name, b =>
{
b.NotNullable(true);
});
}}
public class CustomLocationMapping : ClassMapping<CustomLocation>{
public CustomLocationMapping(){
Table("CustomLocation");
Property(a => a.ZipCode, b =>
{
b.NotNullable(true);
});
Property(a => a.Name, b =>
{
b.NotNullable(true);
});
}}
我的目标是我有一个由脚本自动更新的 Location
表和一个 CustomLocation
表,如果缺少某些位置,用户可以在其中添加位置(或国外).
My target is that I have a Location
table that is being updated automatically by a script and a CustomLocation
table where the user can add locations if there are some missing (or outside the country).
我的问题是,我不知道如何将其正确映射到 Customer
,它可以是 Location
或 CustomLocation
.
My problem is, that I don't know how to properly map this to the Customer
that it can be both Location
or CustomLocation
.
有什么想法吗?提前致谢.
Any ideas? Thanks in advance.
推荐答案
您不能将一个属性映射到两个不同表中的两列.NHibernate 如何知道使用哪个表?您还将失去该列的参照完整性.
You cannot map one property to two columns in two different tables. How would NHibernate know, which table to use? You would also lose the referential integrity for that column.
但是,您的目标可以通过使用稍微不同的方法来实现:对于相同的结构,不要使用两个表,只需使用一个具有以下类表示的 Location
-表:
However, your goal can be achieved by using a slightly different approach: Instead of using two tables for the same structure, just use one Location
-table with the following class representation:
public class Location
{
public virtual int Id { get; set; }
public virtual string ZipCode { get; set; }
public virtual string Name { get; set; }
public virtual bool IsSystem { get; set; } // just use a boolean column in the table for this one
}
您的脚本可以插入/更新/删除 IsSystem == true
的所有行并忽略其余行.当用户添加条目时,只需设置IsSystem = false
.
Your script can insert / update / delete all the rows where IsSystem == true
and ignore the rest. When the user adds an entry, just set IsSystem = false
.
这篇关于模型中一个属性的多个数据库表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!