Ok, this has been a rather frustrating experience :) I am trying to work with an interface based domain model and I can get ALMOST everything working with the exception of the ability to actually save data
Here is what I have so far.
public interface IEntity {
Guid Id {get;set;}
}
public interface IProduct : IEntity {
string Name {get;set;}
string SKU {get;set;}
decimal MSRP {get;set;}
}
public class Product : IProduct {
public virtual Guid Id {get;set;}
public virtual string Name {get;set;}
public virtual string SKU {get;set;}
public virtual decimal MSRP {get;set;}
}
public interface IOrder : IEntity {
DateTime CreatedOn {get;set;}
IList<IOrderLine> Lines {get;set;}
}
public class Order : IOrder {
public virtual Guid Id {get;set;}
public virtual DateTime CreatedOn {get;set;}
public virtual IList<IOrderLine> Lines {get;set;}
}
public interface IOrderLine : IEntity {
IProduct Product {get;set;}
int Qty {get;set;}
decimal Price {get;set;}
}
public class OrderLine : IOrderLine {
public virtual Guid Id {get;set;}
public virtual IProduct Product {get;set;}
public virtual int Qty {get;set;}
public virtual decimal Price {get;set;}
}
public class ProductMap : ClassMap<IProduct>
{
public ProductMap() {
Id(x => x.Id);
Map(x => x.Name);
Map(x => x.SKU);
Map(x => x.MSRP);
}
}
public class OrderMap : ClassMap<IOrder>
{
public OrderMap() {
Id(x => x.Id);
Map(x => x.CreatedOn);
HasMany(x => x.Lines)
.KeyColumns.Add("Id");
}
}
public class OrderLineMap : ClassMap<IOrderLine>
{
public OrderLineMap() {
Id(x => x.Id);
Map(x => x.Qty);
Map(x => x.Price);
References(x => x.Product)
.PropertyRef(x => x.Id)
.ForeignKey("productId");
}
}
public static class NHibernateUtils
{
public static ISessionFactory CreateSessionFactory(IPersistenceConfigurer persistenceConfigurer)
{
return Fluently.Configure()
.Database(persistenceConfigurer)
.Mappings(m =>
{
m.FluentMappings.Add<ProductMap>();
m.FluentMappings.Add<OrderLineMap>();
m.FluentMappings.Add<OrderMap>();
})
.ExposeConfiguration(c => new SchemaExport(c).Create(false, true))
.BuildConfiguration()
.BuildSessionFactory();
}
}
This works to create a valid scheme (I am testing sing Sqlite and can see the db created correctly). The issue is when I try to save an actual entity.
var p = new Product() { Name = "Product Sample", SKU = "12345", MSRP = 1.0 };
var sessionFactory = NHibernateUtils.CreateSessionFactory(...);
using (var session = sesionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
session.Save(p);
transaction.Commit();
}
}
This fails with an error "no persister for Product"
ok, I can see that -- so next I tried this
session.Save((IProduct)p);
and that gave me the error "no persister for IProduct"
So what am I missing?
Note: Here is a link to a gist that actually shows the issue in a running console app https://gist.github.com/ravensorb/14193136002adbb3ec2fac07c026f921