This project is read-only.

Querying Custom Entity with Fluent Mapping

Topics: Writing modules
Sep 19, 2012 at 4:57 AM
Edited Sep 19, 2012 at 5:07 AM

Here is what I try to achieve: I want to be able to get and save records from existing table which can have different naming conventions that required by Orchard Records.

For the sake of testing I changed name of table to be exactly the same as required for automapping: Test_Ecommerce_ProductEntity (where Test.Ecommerce is name of my module). Then I created entity and fluent nhibernate mapping for it:

public class ProductEntity
  public virtual int Id { get; set; }
  public virtual string Name { get; set; }
  public virtual string ShortDescription { get; set; }

public class ProductEntityMap : ClassMap<ProductEntity>
  public ProductEntityMap()
    Id(x => x.Id);
    Map(x => x.Name, "Name").Length(50).Not.Nullable();
    Map(x => x.ShortDescription, "ShortDescription").Length(200).Not.Nullable();

To avoid picking this entity by automapping I put it in namespace that ends with .Entities. I created simple service for testing. I added mapping for my custom entity and checked that mapping exists in mappings collection.

public class MyService : IMyService
  private readonly ISessionLocator sessionLocator;
  private readonly ISessionFactoryHolder sessionFactoryHolder;

  public MyService(ISessionLocator sessionLocator, ISessionFactoryHolder sessionFactoryHolder)
    this.sessionLocator = sessionLocator;
    this.sessionFactoryHolder = sessionFactoryHolder;

    var config = sessionFactoryHolder.GetConfiguration();
    var fluentCfg = Fluently.Configure(config);
    fluentCfg.Mappings(m => m.FluentMappings.AddFromAssemblyOf<ProductEntity>()).BuildConfiguration();

  public List<ProductEntity> GetProducts()
     var products = new List<ProductEntity>();
     using (var session = sessionLocator.For(typeof(ProductEntity)))
       products = session.Linq<ProductEntity>().ToList();

     return products;

However, GetProducts always return empty list. No errors. SQL Profiler does not show any request to database.

To prove that general approach is working I moved my entity to .Models namespace and since entity has valid namings for automapping and table name is left suitable for Orchard, I received my products back

I tried to compare mappings for Product with automapping and with fluent mapping, but I can't see what can be wrong there. I must be missing something but I cannot see what. Hopefully someone tried something similar. Could you give some ideas what to check?

Sep 21, 2012 at 1:36 AM
Edited Sep 21, 2012 at 1:36 AM

After debugging I found out that my custom entity does not have a persister. My mapping is added to configuration after session factory is already built.

Now I have more specific questions: what is the best place and approach to inject my custom mapping into configuration before session factory is created. Is there an interface I need to implement or event to subscribe?