1
我正在創建一對多關係的NHibenate應用程序。像城市和州數據一樣。 市臺流利的NHibernate多對一的映射
CREATE TABLE [dbo].[State](
[StateId] [varchar](2) NOT NULL primary key,
[StateName] [varchar](20) NULL)
CREATE TABLE [dbo].[City](
[Id] [int] primary key IDENTITY(1,1) NOT NULL ,
[State_id] [varchar](2) NULL refrences State(StateId),
[CityName] [varchar](50) NULL)
我的映射如下
public CityMapping()
{
Id(x => x.Id);
Map(x => x.State_id);
Map(x => x.CityName);
HasMany(x => x.EmployeePreferedLocations)
.Inverse()
.Cascade.SaveUpdate();
References(x => x.State)
//.Cascade.All();
//.Class(typeof(State))
//.Not.Nullable()
.Cascade.None()
.Column("State_id");
}
public StateMapping()
{
Id(x => x.StateId)
.GeneratedBy.Assigned();
Map(x => x.StateName);
HasMany(x => x.Jobs)
.Inverse();
//.Cascade.SaveUpdate();
HasMany(x => x.EmployeePreferedLocations)
.Inverse();
HasMany(x => x.Cities)
// .Inverse()
.Cascade.SaveUpdate();
//.Not.LazyLoad()
}
型號如下:
[Serializable]
public partial class City
{
public virtual System.String CityName { get; set; }
public virtual System.Int32 Id { get; set; }
public virtual System.String State_id { get; set; }
public virtual IList<EmployeePreferedLocation> EmployeePreferedLocations { get; set; }
public virtual JobPortal.Data.Domain.Model.State State { get; set; }
public City(){}
}
public partial class State
{
public virtual System.String StateId { get; set; }
public virtual System.String StateName { get; set; }
public virtual IList<City> Cities { get; set; }
public virtual IList<EmployeePreferedLocation> EmployeePreferedLocations { get; set; }
public virtual IList<Job> Jobs { get; set; }
public State()
{
Cities = new List<City>();
EmployeePreferedLocations = new List<EmployeePreferedLocation>();
Jobs = new List<Job>();
}
//public virtual void AddCity(City city)
//{
// city.State = this;
// Cities.Add(city);
//}
}
我的單元測試代碼如下。
City city = new City();
IRepository<State> rState = new Repository<State>();
Dictionary<string, string> critetia = new Dictionary<string, string>();
critetia.Add("StateId", "TX");
State frState = rState.GetByCriteria(critetia);
city.CityName = "Waco";
city.State = frState;
IRepository<City> rCity = new Repository<City>();
rCity.SaveOrUpdate(city);
City frCity = rCity.GetById(city.Id);
問題是,我無法插入記錄。錯誤在下面。
"Invalid index 2 for this SqlParameterCollection with Count=2."
但不會來的錯誤,如果我在CityMapping文件發表評論STATE_ID測繪領域。我不知道我做了什麼錯誤。如果不給映射Map(x => x.State_id);該字段的值爲空,這是期望的。請幫我解決這個問題。
點#1是錯誤的根本原因:state_id在同一個類中映射兩次。 – 2010-03-25 00:57:16
嗨Jamie/Darin 如果我不把sate_Id放在City表中,那麼當我獲取城市表時,如何獲取state_id?我不想在獲取城市表格時讀取狀態表。 – Jit 2010-03-26 18:42:18
假設你有一個城市,你可以瀏覽關聯:'city.State.StateId'。 – 2010-03-26 19:50:46