Why does Fluent NHibernate AutoMappings add an underscore to Id (e.g. Entity_id)?

后端 未结 2 592
醉梦人生
醉梦人生 2021-01-22 15:28

Hi using fluent nibernate automappings

to map this

    public virtual int Id { get; set; }
    /*...snip..*/
    public virtual MapMarkerIcon MapMarkerI         


        
相关标签:
2条回答
  • 2021-01-22 16:15

    You need an Id convention.

    See http://wiki.fluentnhibernate.org/Available_conventions and http://wiki.fluentnhibernate.org/Convention_shortcut

    0 讨论(0)
  • 2021-01-22 16:18

    None of the above links work. Here's the solution with links to current Fluent NHibernate & automapping documentation.

    The issue (a simple example):

    Say you have the simple example (from fluent's wiki) with an Entity and it's Value Objects in a List:

    public class Product
    {
      public virtual int Id { get; set; }
      //..
      public virtual Shelf { get; set; }
    }
    
    public class Shelf
    {
      public virtual int Id { get;  set; }
      public virtual IList<Product> Products { get; set; }
    
      public Shelf()
      {
        Products = new List<Product>();
      }
    }
    

    With tables which have e.g.

    Shelf 
    id int identity
    
    Product 
    id int identity 
    shelfid int
    

    And a foreign key for shelfid -> Shelf.Id


    You would get the error: invalid column name ... shelf_id


    Solution:

    Add a convention, it can be system wide, or more restricted.

    ForeignKey.EndsWith("Id")
    

    Code example:

    var cfg = new StoreConfiguration();
    var sessionFactory = Fluently.Configure()
      .Database(/* database config */)
      .Mappings(m =>
        m.AutoMappings.Add(
          AutoMap.AssemblyOf<Product>(cfg)
              .Conventions.Setup(c =>
                  {
                      c.Add(ForeignKey.EndsWith("Id"));
                  }
        )
      .BuildSessionFactory();
    

    Now it will automap the ShelfId column to the Shelf property in Product.


    More info

    Wiki for Automapping

    Table.Is(x => x.EntityType.Name + "Table")
    PrimaryKey.Name.Is(x => "ID")
    AutoImport.Never()
    DefaultAccess.Field()
    DefaultCascade.All()
    DefaultLazy.Always()
    DynamicInsert.AlwaysTrue()
    DynamicUpdate.AlwaysTrue()
    OptimisticLock.Is(x => x.Dirty())
    Cache.Is(x => x.AsReadOnly())
    ForeignKey.EndsWith("ID")
    

    See more about Fluent NHibernate automapping conventions

    0 讨论(0)
提交回复
热议问题