How do I make an IgnoreProperty convention in fluent nhibernate? - fluent-nhibernate

public class MyObjectMap : IAutoMappingOverride<MyObject>
{
public void Override(AutoMapping<MyObject> mapping)
{
mapping.IgnoreProperty(x => x.InterfaceProperty);
}
}
I am currently doing this in every map... how can I make this into a convention? I am adding conventions like so:
private Action<IConventionFinder> GetConventions()
{
return c =>
{
c.Add<ForeignKeyConvention>();
c.Add<HasManyConvention>();
c.Add<HasManyToManyConvention>();
c.Add<ManyToManyTableNameConvention>();
c.Add<PrimaryKeyConvention>();
c.Add<ReferenceConvention>();
c.Add<TableNameConvention>();
};
}

I think this is not something related to Convention,however it is subject to Mapping Overriding, try this:
public class AutoMapDefaultConfig : DefaultAutomappingConfiguration
{
public override bool ShouldMap(FluentNHibernate.Member member)
{
if (member.Name == "InterfaceProperty")
return false;
return base.ShouldMap(member);
}
}
i haven't try this actually, but I think it may help,and notice that the DefaultAutomappingConfiguration is in Fluent-NHibernate V1.1

Related

How to automap a collection of components with Fluent NHibernate?

All of my entities and value objects implement marker interfaces IEntity and IValueObject. I have set them up to be treated as components like so:
public override bool IsComponent(Type type)
{
return typeof(IValueObject).IsAssignableFrom(type);
}
public override bool ShouldMap(Type type)
{
return typeof(IEntity).IsAssignableFrom(type) || typeof(IValueObject).IsAssignableFrom(type);
}
Unfortunately, this does not seem to allow entities that have collections of value objects to be automapped as component collections. For example:
public class MyEntity : IEntity
{
public IList<MyValueObject> Objects { get; set; }
}
public class MyValueObject : IValueObject
{
public string Name { get; set; }
public string Value { get; set; }
}
Is there any way to define a convention such that, any time an IEntity has an IList of a type that implements IValueObject, it gets mapped as if I had specified:
HasMany(x => x.Objects)
.Component(x => {
x.Map(m => m.Name);
x.Map(m => m.Value);
});
What I don't want to do is have to manually do these overrides for every class and write out each property for the value object again and again.
Create a new class that inherits from HasManyStep (FluentNHibernate.Automapping.Steps).
Override the ShouldMap() method with something like :
return base.ShouldMap(member) && IsCollectionOfComponents(member)
Add your logic to :
public void Map(ClassMappingBase classMap, Member member)
{ ... }
Replace the default step with your new one :
public class MyMappingConfiguration : DefaultAutomappingConfiguration
{
public override IEnumerable<IAutomappingStep> GetMappingSteps(AutoMapper mapper, IConventionFinder conventionFinder)
{
var steps = base.GetMappingSteps(mapper, conventionFinder);
var finalSteps = steps.Where(c => c.GetType() != typeof(FluentNHibernate.Automapping.Steps.HasManyToManyStep)).ToList();
var idx = finalSteps.IndexOf(steps.Where(c => c.GetType() == typeof(PropertyStep)).First());
finalSteps.Insert(idx + 1, new MyCustomHasManyStep(this));
return finalSteps;
}
}
Note : You could also get the original source code of HasManyStep.cs and copy it to your project to introduce your custom logic.

Override default Fluent NHibernate Column Mapping

I am trying to find the syntax for changing the automap behavior of Fluent NHibernate.
How would I modify the code below to map the UserId property to a column named UserIdentifier (as an example)?
public class MyTypeMap : ClassMap<MyType>
{
public MyTypeMap()
{
Table("MyTypes");
Id(x => x.InstanceId).GeneratedBy.Guid().UnsavedValue(Guid.Empty);
Map(x=> x.UserId);
}
}
Thanks
public class MyTypeMap : ClassMap<MyType>
{
public MyTypeMap()
{
Table("MyTypes");
Id(x => x.InstanceId).GeneratedBy.Guid().UnsavedValue(Guid.Empty);
Map(x=> x.UserId).Column("UserIdentifier");
}
}
public class MyTypeMap : ClassMap<MyType>
{
public MyTypeMap()
{
Id (x => x.InstanceId).Column ("UserIdentifier").GeneratedBy.Guid().UnsavedValue(Guid.Empty);
}
}

Cascade Saves with Fluent NHibernate AutoMapping

How do I "turn on" cascading saves using AutoMap Persistence Model with Fluent NHibernate?
As in:
I Save the Person and the Arm should also be saved. Currently I get
"object references an unsaved transient instance - save the transient instance before flushing"
public class Person : DomainEntity
{
public virtual Arm LeftArm { get; set; }
}
public class Arm : DomainEntity
{
public virtual int Size { get; set; }
}
I found an article on this topic, but it seems to be outdated.
This works with the new configuration bits. For more information, see http://fluentnhibernate.wikia.com/wiki/Converting_to_new_style_conventions
//hanging off of AutoPersistenceModel
.ConventionDiscovery.AddFromAssemblyOf<CascadeAll>()
public class CascadeAll : IHasOneConvention, IHasManyConvention, IReferenceConvention
{
public bool Accept( IOneToOnePart target )
{
return true;
}
public void Apply( IOneToOnePart target )
{
target.Cascade.All();
}
public bool Accept( IOneToManyPart target )
{
return true;
}
public void Apply( IOneToManyPart target )
{
target.Cascade.All();
}
public bool Accept( IManyToOnePart target )
{
return true;
}
public void Apply( IManyToOnePart target )
{
target.Cascade.All();
}
}
Updated for use with the the current version:
public class CascadeAll : IHasOneConvention, IHasManyConvention, IReferenceConvention
{
public void Apply(IOneToOneInstance instance)
{
instance.Cascade.All();
}
public void Apply(IOneToManyCollectionInstance instance)
{
instance.Cascade.All();
}
public void Apply(IManyToOneInstance instance)
{
instance.Cascade.All();
}
}
The easiest way I've found to do this for a whole project is to use DefaultCascade:
.Conventions.Add( DefaultCascade.All() );
Go to "The Simplest Conventions" section on the wiki, for this, and a list of others.
Here's the list from the Wiki:
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")
A word of warning - some of the method names in the Wiki may be wrong. I edited the Wiki with what I could verify (i.e. DefaultCascade and DefaultLazy), but can't vouch for the rest. But you should be able to figure out the proper names with Intellisense if the need arises.
The Convention Method Signatures have changed. For the new answer that does exactly what this question asks see THIS QUESTION.
You can also make cascading the default convention for all types. For example (using the article you linked to as a starting point):
autoMappings.WithConvention(c =>
{
// our conventions
c.OneToOneConvention = o => o.Cascade.All();
c.OneToManyConvention = o => o.Cascade.All();
c.ManyToOneConvention = o => o.Cascade.All();
});

Is it possible to use private field conventions for Fluent NHibernate Automapping?

How can I map to a private field with fluent NHibernate AutoPersistenceModel?
public class A
{
private List<B> myField;
public A()
{
myField = new List<B>();
}
public IList<B> MyBs
{
get { return myField; }
}
}
Is there a fieldconvention for the AutoPersistence model or do I have to use separate mappings for classes with fields?
The answer:
It's not possible yet. Maybe I should submit a patch for it...
I know this is not does not answer the auto mapping, but to assist those who get this searching for private field mapping.
You can now use the following code:
public class A
{
private List<B> myBs;
public A()
{
myField = new List<B>();
}
public IList<B> MyBs
{
get { return myField; }
}
}
With a mapping like this
public class AMap : ClassMap<A> {
public AMap() {
HasMany(x => x.MyBs).Access.CamelCaseField()
}
}
It's been a while since this question was asked, but it's probably worth posting this answer in case others find this question.
The Fluent NHibernate Wiki has some information on 3 possible workarounds.
http://wiki.fluentnhibernate.org/Fluent_mapping_private_properties

How do you map an enum as an int value with fluent NHibernate?

Question says it all really, the default is for it to map as a string but I need it to map as an int.
I'm currently using PersistenceModel for setting my conventions if that makes any difference.
Update
Found that getting onto the latest version of the code from the trunk resolved my woes.
The way to define this convention changed sometimes ago, it's now :
public class EnumConvention : IUserTypeConvention
{
public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
{
criteria.Expect(x => x.Property.PropertyType.IsEnum);
}
public void Apply(IPropertyInstance target)
{
target.CustomType(target.Property.PropertyType);
}
}
So, as mentioned, getting the latest version of Fluent NHibernate off the trunk got me to where I needed to be. An example mapping for an enum with the latest code is:
Map(quote => quote.Status).CustomTypeIs(typeof(QuoteStatus));
The custom type forces it to be handled as an instance of the enum rather than using the GenericEnumMapper<TEnum>.
I'm actually considering submitting a patch to be able to change between a enum mapper that persists a string and one that persists an int as that seems like something you should be able to set as a convention.
This popped up on my recent activity and things have changed in the newer versions of Fluent NHibernate to make this easier.
To make all enums be mapped as integers you can now create a convention like so:
public class EnumConvention : IUserTypeConvention
{
public bool Accept(IProperty target)
{
return target.PropertyType.IsEnum;
}
public void Apply(IProperty target)
{
target.CustomTypeIs(target.PropertyType);
}
public bool Accept(Type type)
{
return type.IsEnum;
}
}
Then your mapping only has to be:
Map(quote => quote.Status);
You add the convention to your Fluent NHibernate mapping like so;
Fluently.Configure(nHibConfig)
.Mappings(mappingConfiguration =>
{
mappingConfiguration.FluentMappings
.ConventionDiscovery.AddFromAssemblyOf<EnumConvention>();
})
./* other configuration */
Don't forget about nullable enums (like ExampleEnum? ExampleProperty)! They need to be checked separately. This is how it's done with the new FNH style configuration:
public class EnumConvention : IUserTypeConvention
{
public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
{
criteria.Expect(x => x.Property.PropertyType.IsEnum ||
(x.Property.PropertyType.IsGenericType &&
x.Property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) &&
x.Property.PropertyType.GetGenericArguments()[0].IsEnum)
);
}
public void Apply(IPropertyInstance target)
{
target.CustomType(target.Property.PropertyType);
}
}
this is how I've mapped a enum property with an int value:
Map(x => x.Status).CustomType(typeof(Int32));
works for me!
For those using Fluent NHibernate with Automapping (and potentially an IoC container):
The IUserTypeConvention is as #Julien's answer above: https://stackoverflow.com/a/1706462/878612
public class EnumConvention : IUserTypeConvention
{
public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
{
criteria.Expect(x => x.Property.PropertyType.IsEnum);
}
public void Apply(IPropertyInstance target)
{
target.CustomType(target.Property.PropertyType);
}
}
The Fluent NHibernate Automapping configuration could be configured like this:
protected virtual ISessionFactory CreateSessionFactory()
{
return Fluently.Configure()
.Database(SetupDatabase)
.Mappings(mappingConfiguration =>
{
mappingConfiguration.AutoMappings
.Add(CreateAutomappings);
}
).BuildSessionFactory();
}
protected virtual IPersistenceConfigurer SetupDatabase()
{
return MsSqlConfiguration.MsSql2008.UseOuterJoin()
.ConnectionString(x =>
x.FromConnectionStringWithKey("AppDatabase")) // In Web.config
.ShowSql();
}
protected static AutoPersistenceModel CreateAutomappings()
{
return AutoMap.AssemblyOf<ClassInAnAssemblyToBeMapped>(
new EntityAutomapConfiguration())
.Conventions.Setup(c =>
{
// Other IUserTypeConvention classes here
c.Add<EnumConvention>();
});
}
*Then the CreateSessionFactory can be utilized in an IoC such as Castle Windsor (using a PersistenceFacility and installer) easily. *
Kernel.Register(
Component.For<ISessionFactory>()
.UsingFactoryMethod(() => CreateSessionFactory()),
Component.For<ISession>()
.UsingFactoryMethod(k => k.Resolve<ISessionFactory>().OpenSession())
.LifestylePerWebRequest()
);
You could create an NHibernate IUserType, and specify it using CustomTypeIs<T>() on the property map.
You should keep the values as int / tinyint in your DB Table. For mapping your enum you need to specify mapping correctly. Please see below mapping and enum sample,
Mapping Class
public class TransactionMap : ClassMap Transaction
{
public TransactionMap()
{
//Other mappings
.....
//Mapping for enum
Map(x => x.Status, "Status").CustomType();
Table("Transaction");
}
}
Enum
public enum TransactionStatus
{
Waiting = 1,
Processed = 2,
RolledBack = 3,
Blocked = 4,
Refunded = 5,
AlreadyProcessed = 6,
}