我有以下表格:功能NHibernate的hasMany關係無法插入
- 業主= ID(主鍵),名字,姓氏,EmailAddress的,題目;
- PROPERTY = Id(主鍵),Type,NumberOfBrooms,Address1,Address2,City,County,PostCode,LandlordId(業主實體的外鍵);
我的域類:
public class Landlord:BaseEntity
{
public virtual string Title { get; set; }
public virtual string Surname { get; set; }
public virtual string FirstName { get; set; }
public virtual string EmailAddress { get; set; }
public virtual IList<Property> Properties { get; set; }
public Landlord()
{
Properties = new List<Property>();
}
}
public class Property:BaseEntity
{
public virtual string Type { get; set; }
public virtual int NumberOfBedrooms { get; set;}
public virtual string Address1 { get; set; }
public virtual string Address2 { get; set; }
public virtual string City { get; set; }
public virtual string County { get; set; }
public virtual string PostCode { get; set; }
public virtual Landlord Landlord { get; set; }
}
我流利的NHibernate的地圖是:
public sealed class LandlordMap:ClassMap<Landlord>
{
public LandlordMap()
{
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.Title);
Map(x => x.Surname);
Map(x => x.FirstName);
Map(x => x.EmailAddress);
HasMany(x => x.Properties)
.KeyColumns.Add("LandlordId")
.Inverse()
.Cascade.All();
Table("LANDLORD");
}
}
public sealed class PropertyMap:ClassMap<Property>
{
public PropertyMap()
{
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.Type);
Map(x => x.NumberOfBedrooms);
Map(x => x.Address1);
Map(x => x.Address2);
Map(x => x.City);
Map(x => x.County);
Map(x => x.PostCode);
References(x => x.Landlord, "LandlordId");
Table("PROPERTY");
}
}
要測試房東被保存到數據庫中,我有以下代碼:
public class Program
{
static void Main(string[] args)
{
ILandlordRepository rep = new LandlordRepository();
//Create property object
Property p1 = new Property
{
Address1 = "123 LA Road",
Address2 = "Bilston",
City = "Harlem",
County = "West Mids",
NumberOfBedrooms = 2,
PostCode = "wv134wd",
Type = "Bungalow"
};
//Create landlord and assign property
var landlord = new Landlord();
landlord.Title = "Dr";
landlord.FirstName = "Rohit";
landlord.Surname = "Kumar";
landlord.EmailAddress = "[email protected]";
landlord.Properties.Add(p1);
//Add to the database
rep.SaveOrUpdate(landlord);
Console.ReadKey();
}
}
當我打電話SaveOrUpdate我得到這個錯誤:
could not insert: [Homes4U.Service.DomainClasses.Property][SQL: INSERT INTO PROPERTY (Type, NumberOfBedrooms, Address1, Address2, City, County, PostCode, LandlordId) VALUES (?, ?, ?, ?, ?, ?, ?, ?); select SCOPE_IDENTITY()]
現在有人爲什麼會發生這種情況嗎?
我該如何解決? – user1737371
對不起,我是NHibernate的一個新手,但不是NHiberate保存父項的重點,它會照顧保存子項元素在這種情況下的屬性? – user1737371
如果這是你所尋求的行爲,你需要扭轉關係(取反)。 –