How to automap Table-per-class hierarchy in S#arp architecture - fluent-nhibernate

I am pretty new to S#harp architecture and fluent nhibernate. I was trying to build a sample solution using the template.
MappingIntegrationTest fails for me when I try to run it for the following domains
public class Component
{
public virtual string comp { get; set; }
}
public class Parent : Entity
{
public virtual string Type { get; set; }
}
public class Child1: Parent
{
public virtual Component Blah { get; set }
}
The ParentMap looks like following:
public class ParentMap : IAutoMappingOverride<Parent>
{
public void Override(AutoMapping<Parent> mapping)
{
mapping.DiscriminateSubClassesOnColumn("Type")
.SubClass<Child1>(m =>
{
m.Component(c => c.Blah, c =>
{
c.Map(x => x.comp , "comp");
}
}
}
}
The mapping integration tests fail for me
* Database was not configured through Database method.
----> NHibernate.MappingException : An association from the table Parent refers to an unmapped class: Component
Do I need to remove these classes from AutoMapper?

Related

exception:"type was not mapped" in entityframework codefirst with layers

i'm trying to apply LAYERS Concept on demo project developed using mvc and entity framework both
Data Annotations : for validations in Data Access Layer and
Fluent API : for mapping and tables relations
Problem : DbContext didn't Create DB and there is a Runtime Exception :
The type 'Domain.DataLayer.Member' was not mapped. Check that the type has not been explicitly excluded by using the Ignore method or NotMappedAttribute data annotation. Verify that the type was defined as a class, is not primitive, nested or generic, and does not inherit from EntityObject.
Code : my solutions consists of :
1- class library (Domain.Classes project): where i wrote all of my classes
public class Member
{
public int Id { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string FullName { get; set; }
}
2- DAL (Domain.DataLayer project): also another class library and i referenced domain.classes
namespace Domain.DataLayer.Repositories
{
[MetadataType(typeof(MemberMetadata))]
public partial class Member : Classes.Member , IValidatableObject
{
public Member()
{
Tasks = new HashSet<Task>();
History = new HashSet<Commint>();
}
public string ConfirmPassword { get; set; }
public HashSet<Task> Tasks { get; set; }
public HashSet<Commint> History { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var result = new List<ValidationResult>();
if (!string.Equals(Password,ConfirmPassword))
{
result.Add(new ValidationResult("mismatch pwsd", new[] {"ConfirmPassword" }));
}
return result;
}
}
}
and i used repository pattern :
public class MemberRepository : IRepository<Member>
{
public Task<IQueryable<Member>> GetAllEntities()
{
return Task<IQueryable<Member>>.Factory.StartNew(() => new Context().Members.AsQueryable());
}
}
3-BLL : for sake of simplicity : there is no Business Logic Layer
4- PL (Domain.Application MVC Project) : Member Controller :
public async Task<ActionResult> Index()
{
var members = await _repository.GetAllEntities();
return View(members);
}
Note : i depended on DbContext to create DB with name like : Domain.DataLayer.Context but it didn't craete DB so i created the DB and passed the connectionString through Context constructor like this :
namespace Domain.DataLayer
{
public class Context : DbContext
{
public Context(): base("InterviewDemo") // i tried also base("name=InterviewDemo")
{
}
public DbSet<Member> Members { get; set; }
public DbSet<Task> Tasks { get; set; }
public DbSet<Commint> TaskHistory { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new MemberConfig());
modelBuilder.Configurations.Add(new TaskConfig());
modelBuilder.Configurations.Add(new CommintConfig());
base.OnModelCreating(modelBuilder);
}
}
}

NHibernate: cannot resolve inherited id property

I have the entity defined below:
public class Foo : Entity<Foo.FooId>
{
public class FooId
{
public virtual String Bar { get; protected internal set; }
public virtual Int32 Buzz { get; protected internal set; }
}
// ...
}
And here's the base class:
public abstract class Entity<T> : IEquatable<Entity<T>>
{
public virtual T Id { get; protected internal set; }
// ...
}
I'm going to map the "Id" property as a "composite key", so I've added the following mapping class:
public class FooMap : ClassMapping<Foo>
{
public FooMap()
{
ComponentAsId(x => x.Id, m =>
{
m.Property(p => p.Bar);
m.Property(p => p.Buzz);
});
}
}
And that's all pretty nice, but I get an error with the following querying attempt:
session.QueryOver<Foo>()
.Where(m => m.Id.Bar == "a" &&
m.Id.Buzz == 2).List();
The error I get is:
NHibernate.QueryException : could not resolve property: Id of: Foo
It's quite strange, because by removing the base class and encapsulating everything within "Foo", it works like a charm.
Thanks in advance.
This was a bug and reported as NH-3105. It is now fixed in the most recent of the source code and will be released as 3.3.3.GA.

C# fluent nhibernate

How should the following mapping configuration be solved?
public abstract class RepositoryEntity
{
public virtual int Id { get; set; }
}
public class Descriptor : RepositoryEntity
{
public virtual String Name { get; set; }
public virtual DateTime Timestamp { get; set; }
}
public class Proxy<TDescriptor> : RepositoryEntity
{
public virtual TDescriptor Descriptor { get; set; }
public virtual Byte[] SerializedValue { get; set; }
};
public class TestUnit : Proxy<Descriptor>
{
};
I receive problems when testing the TestUnit mapping - it says it's impossible to map the item with generic parameters. This happens if I attempt to map every class from the specified before.
If I attempt to map everything, except Proxy<T>, then I receive that there is no persister for the 'TestUnit'.
If I stop inheriting TestUnit from Proxy<Descriptor>, the mapping test works fine.
Does Fluent NHibernate have possibility to automap types inherited from some concrete Class<T> template? Could you help me with mapping these entities?
I used a combination of Fluent and Auto mappings.
Fluent mappings should be used for generics.
Configuration = Fluently.Configure()
.Database(SQLiteConfiguration.Standard.ShowSql().InMemory)
.Mappings(x =>
{
x.FluentMappings.AddFromAssemblyOf<RepositoryEntity>();
x.AutoMappings.Add(autoPersistenceModel);
});

NHibernate DuplicateMappingException when mapping abstract class and subclass

I have an abstract class and subclasses of this, and I want to map this to my database using NHibernate. I'm using Fluent and how to do the mapping. But when I add the mapping of the subclass an NHibernate.DuplicateMappingException is thrown when it is mapping. Why?
Here are my (simplified) classes:
public abstract class FieldValue
{
public int Id { get; set; }
public abstract object Value { get; set; }
}
public class StringFieldValue : FieldValue
{
public string ValueAsString { get; set; }
public override object Value
{
get
{
return ValueAsString;
}
set
{
ValueAsString = (string)value;
}
}
}
And the mappings:
public class FieldValueMapping : ClassMap<FieldValue>
{
public FieldValueMapping()
{
Id(m => m.Id).GeneratedBy.HiLo("1");
// DiscriminateSubClassesOnColumn("type");
}
}
public class StringValueMapping : SubclassMap<StringFieldValue>
{
public StringValueMapping()
{
Map(m => m.ValueAsString).Length(100);
}
}
And the exception:
> NHibernate.MappingException : Could not compile the mapping document: (XmlDocument)
----> NHibernate.DuplicateMappingException : Duplicate class/entity mapping NamespacePath.StringFieldValue
Any ideas?
Discovered the problem. It turned out that I did reference the same Assembly several times in the PersistenceModel used to configure the database:
public class MappingsPersistenceModel : PersistenceModel
{
public MappingsPersistenceModel()
{
AddMappingsFromAssembly(typeof(FooMapping).Assembly);
AddMappingsFromAssembly(typeof(BarMapping).Assembly);
// Where FooMapping and BarMapping is in the same Assembly.
}
}
Apparently this is not a problem for ClassMap-mappings. But for SubclassMap it doesn't handle it as well, causing duplicate mappings - and hence the DuplicateMappingException. Removing the duplicates in the PersistenceModel fixes the problem.
If you are using automappings together with explicit mappings then fluent can generate two mappings for the same class.

Fluent NHibernate: Example of a one-to-many relationship on an abstract class of a table-per-subclass implementation

I've been trying for ages to find an example (because I can't get it to work myself) of the correct mapping for a one-to-many relationship on an abstract class of a table-per-subclass implementation, in fluent nHibernate.
An example below: I'm looking to map the list of Fines on the Debt abstract base class to the Fine class.
If anyone knows of any tutorial or example they've come across before please let me know.
public abstract class Entity
{
public int Id { get; set; }
}
public abstract class Debt : Entity
{
public decimal Balance { get; set; }
public IList<Fine> Fines { get; set; }
public Debt()
{
Fines = new List<Fine>();
}
}
public class CarLoan : Debt
{
}
public class CreditCard : Debt
{
}
public class LoanApplication : Entity
{
public IList<Debt> ExistingDebts { get; set; }
public LoanApplication()
{
ExistingDebts = new List<Debt>();
}
}
public class Fine
{
public Int64 Cash { get; set; }
}
Can you tell us where exactly you're having difficulty? What have you tried?
Obviously, you'll need to declare all of your members as virtual (I assume this was an oversight in the example).
Basically, though, it would look like this:
public DebtMap : ClassMap<Debt>
{
public DebtMap()
{
Id(x => x.Id);
HasMany(x => x.Fines);
}
}
public FineMap : ClassMap<Fine>
{
public FineMap()
{
Id(x => x.Id);
// map other members
}
}
public CarLoanMap : SubclassMap<CarLoan> { }
public CreditCardMap : SubclassMap<CreditCard> { }