1
這是一個普遍的問題,我敢肯定它很常見,但是我還沒有找到任何東西(或者我不知道要搜索什麼) 。在流利的NHibernate中插入一個有現有子項的父實體
我有我的項目下列實體:
public class User
{
public virtual int Id { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual Unit Unit { get; set; }
}
public class Unit
{
public virtual int Id { get; set;}
public virtual string Name { get; set;}
}
這是如何我已經做了功能NHibernate映射:
public class UserMap : ClassMap<User>
{
public UserMap()
{
Id(x => x.Id).GeneratedBy.Identity().Column("UserId");
Map(x => x.FirstName);
Map(x => x.LastName);
References(x => x.Unit).Column("UnitId");
}
}
public class UnitMap : ClassMap<Unit>
{
public UnitMap()
{
Table("Unit");
LazyLoad();
Id(x => x.Id).GeneratedBy.Identity().Column("UnitId");
Map(x => x.Name).Column("Name").Not.Nullable();
HasMany(x => x.Users).KeyColumn("UnitId");
}
}
現在,這裏是我的問題。如果我只有用戶的單元ID不是一個完整的單元對象,並且該單元已經存在於數據庫(以前創建)中,如何創建一個新用戶? 事情是這樣的:
public class TestClass
{
// Adding a user to a unit example
public void SavingAUser(int unitId)
{
var user = new User
{
FirstName = "TestFirstName",
LastName = "TestLastName",
Unit = new Unit() // <-- I have only the Id of the unit I don't actually have a unit object here I don't want to query the DB to get the full object, I already have the Id
};
var userRepository = new UserRepository();
userRepository.Save(user);
}
}
我怎麼會去這樣的事情。我希望我有道理,如果不是,請讓我知道我會進一步澄清。我也非常確定這是一個非常常見的情況
謝謝,正是我在找的! :) – 2013-02-23 09:40:28