简体   繁体   English

没有外键的FluentNHibernate映射

[英]FluentNHibernate mapping without foreign key

i have this 2 class 我有这两节课

public class Product {
    public virtual Guid Id {get; set;}
    public virtual string Name {get; set;}
    public virtual Description Description {get; set;}
}

public class Description {
    public virtual Guid Id {get; set;}
    public virtual string Suggestion {get; set;}
    public virtual string Composition {get; set;}
}

i've try to map the class with this Mapper class: 我试图用这个Mapper类映射该类:

public class ProductMap : ClassMap<Product>
{
    public ProductMap()
    {
        Id(x => x.Id);
        Map(x => x.Name);
        References(x => x.Description).ForeignKey("Id");
    }
}

Description was related to Product with same Id, so eg Product with Id = 1 will have description in table with Id = 1. Now i try to read data from the table with this: 描述与具有相同Id的产品有关,因此例如Id = 1的产品将在表中具有Id = 1的描述。现在我尝试从表中读取数据:

using (var session = factory.OpenSession())
{
    var testProduct = session.Query<Product>().Where(p => p.Id == 2).Single();
    lblValue.Text = testProduct.Description.Composition;
}

but i get error exception 但我得到错误异常

InnerException: System.Data.SqlClient.SqlException
       Message=Invalid column name 'Description_id'.

i know i've put something wrong in mapper constructor. 我知道我在mapper构造函数中出错了。 Could u guys help me how to map this correctly. 你们可以帮我解决这个问题吗? i dont want to put field Description_id in table Product. 我不想在表Product中放置字段Description_id。 Thanks 谢谢

Change your ProductMap to be like this: 将ProductMap更改为:

public class ProductMap : ClassMap<Product>
{
  public ProductMap()
  {
    Id(x => x.Id);
    Map(x => x.Name);
    References(x => x.Description).Columns("Id");
  }
}

This tells nHibernate to join Products to Description using the "Id" column of the Product entity to the column defined as Id in the DescriptionMap (which also needs to be set to "Id"). 这告诉nHibernate使用Product实体的“Id”列将Description与Description连接到DescriptionMap中定义为Id的列(也需要设置为“Id”)。 Incase you don't already have it I have created a DescriptionMap class which you will also need: 如果您还没有它我已经创建了一个您还需要的DescriptionMap类:

public class DescriptionMap : ClassMap<Description>
{
  public DescriptionMap ()
  {
    Id(x => x.Id);
    Map(x => x.Suggestion);
    Map(x => x.Composition);
  }
}

What CSL mentioned should work, but I would add that the Column Name is actually the second parameter of the References method, so you can simply do this. CSL提到的应该有用,但我想补充一点,Column Name实际上是References方法的第二个参数,所以你可以简单地做到这一点。

public class ProductMap : ClassMap<Product>
{
  public ProductMap()
  {
    Id(x => x.Id);
    Map(x => x.Name);
    References(x => x.Description, "Id");
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM