流畅的NHibernate多对一映射

时间:2010-03-24 22:01:36

标签: nhibernate fluent-nhibernate

我正在创建一个具有一对多关系的NHibenate应用程序。像城市和州的数据。 城市表

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 =&gt; x.State_id); ,则该字段的值为null,这是期望的。请帮我解决这个问题。

1 个答案:

答案 0 :(得分:1)

几点评论:

  1. State_id类和映射中删除此City属性。您已经拥有State属性,因此在您的对象模型中没有任何意义。

  2. Jobs类中的EmployeePreferedLocationsState属性在您的数据库中没有任何相关的列/表(至少是您在此处显示的那个)你有映射的时候。