本文整理汇总了C#中ModelMapper类的典型用法代码示例。如果您正苦于以下问题:C# ModelMapper类的具体用法?C# ModelMapper怎么用?C# ModelMapper使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ModelMapper类属于命名空间,在下文中一共展示了ModelMapper类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: BuildConfiguration
public static Configuration BuildConfiguration(string connStr)
{
var cfg = new Configuration();
// See http://fabiomaulo.blogspot.com/2009/07/nhibernate-configuration-through.html
cfg.DataBaseIntegration(db => {
db.Driver<SqlClientDriver>();
db.Dialect<MsSql2012Dialect>();
db.ConnectionString = connStr; // db.ConnectionStringName = "ConnStr";
db.HqlToSqlSubstitutions = "true 1, false 0, yes 'Y', no 'N'";
// See http://geekswithblogs.net/lszk/archive/2011/07/12/showing-a-sql-generated-by-nhibernate-on-the-vs-build-in.aspx
//db.LogSqlInConsole = true; // Remove if using Log4Net
//db.LogFormattedSql = true;
//db.AutoCommentSql = true;
db.SchemaAction = SchemaAutoAction.Validate; // This correspond to "hbm2ddl.validate", see http://nhforge.org/blogs/nhibernate/archive/2008/11/23/nhibernate-hbm2ddl.aspx
});
var mapper = new ModelMapper();
mapper.Class<Parent>(map => {
map.Id(x => x.Id, m => {
m.Generator(Generators.GuidComb);
m.UnsavedValue(Guid.Empty);
});
map.Version(x => x.RowVersion, m => m.UnsavedValue(0));
map.Property(x => x.Description);
});
cfg.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
return cfg;
}
开发者ID:gimmi,项目名称:randomhacking,代码行数:31,代码来源:NHibernateConfigurator.cs
示例2: AddNHibernateSessionFactory
public static void AddNHibernateSessionFactory(this IServiceCollection services)
{
// By default NHibernate looks for hibernate.cfg.xml
// otherwise for Web it will fallback to web.config
// we got one under wwwroot/web.config
Configuration config = new Configuration();
config.Configure();
// Auto load entity mapping class
ModelMapper mapper = new ModelMapper();
mapper.AddMappings(Assembly.GetAssembly(typeof(Employee)).GetExportedTypes());
HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
config.AddDeserializedMapping(mapping, "NHibernate.Mapping");
SchemaMetadataUpdater.QuoteTableAndColumns(config);
// Drop & Recreate database schema
new SchemaExport(config).Drop(false, true);
new SchemaExport(config).Create(false, true);
// Register services
services.AddSingleton<ISessionFactory>(provider => config.BuildSessionFactory());
services.AddTransient<ISession>(provider => services.BuildServiceProvider().GetService<ISessionFactory>().OpenSession());
}
开发者ID:csokun,项目名称:WebApiNHibernate,代码行数:25,代码来源:NHibernateSessionFactory.cs
示例3: InitNHibernate
private static void InitNHibernate()
{
lock (LockObject)
{
if (_sessionFactory == null)
{
// Создание NHibernate-конфигурации приложения на основании описаний из web.config.
// После этого вызова, в том числе, из сборки будут извлечены настройки маппинга,
// заданные в xml-файлах.
var configure = new Configuration().Configure();
// Настройка маппинга, созданного при помощи mapping-by-code
var mapper = new ModelMapper();
mapper.AddMappings(new List<Type>
{
// Перечень классов, описывающих маппинг
typeof (DocumentTypeMap),
typeof (DocumentMap),
typeof (DocumentWithVersionMap),
});
// Добавление маппинга, созданного при помощи mapping-by-code,
// в NHibernate-конфигурацию приложения
configure.AddDeserializedMapping(mapper.CompileMappingForAllExplicitlyAddedEntities(), null);
//configure.LinqToHqlGeneratorsRegistry<CompareValuesGeneratorsRegistry>();
//configure.LinqToHqlGeneratorsRegistry<InGeneratorRegistry>();
configure.DataBaseIntegration(x =>
{
x.LogSqlInConsole = true;
x.LogFormattedSql = true;
});
_sessionFactory = configure.BuildSessionFactory();
}
}
}
开发者ID:SergeyMironchuk,项目名称:NHibernateStudy,代码行数:35,代码来源:NHibernateHelper.cs
示例4: ApplyMappings
void ApplyMappings(Configuration config)
{
var mapper = new ModelMapper();
mapper.AddMapping<OutboxEntityMap>();
config.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
}
开发者ID:james-wu,项目名称:NServiceBus.NHibernate,代码行数:7,代码来源:NHibernateOutboxStorage.cs
示例5: MapClassWithIdAndProperty
public void MapClassWithIdAndProperty()
{
var mapper = new ModelMapper();
mapper.Class<MyClass>(ca =>
{
ca.Id("id", map =>
{
map.Column("MyClassId");
map.Generator(Generators.HighLow, gmap => gmap.Params(new { max_low = 100 }));
});
ca.Version("version", map => { });
ca.Property("something", map => map.Length(150));
});
var hbmMapping = mapper.CompileMappingFor(new[] { typeof(MyClass) });
var hbmClass = hbmMapping.RootClasses[0];
hbmClass.Should().Not.Be.Null();
var hbmId = hbmClass.Id;
hbmId.Should().Not.Be.Null();
hbmId.name.Should().Be("id");
hbmId.access.Should().Be("field");
var hbmGenerator = hbmId.generator;
hbmGenerator.Should().Not.Be.Null();
[email protected]().Be("hilo");
hbmGenerator.param[0].name.Should().Be("max_low");
hbmGenerator.param[0].GetText().Should().Be("100");
var hbmVersion = hbmClass.Version;
hbmVersion.name.Should().Be("version");
var hbmProperty = hbmClass.Properties.OfType<HbmProperty>().Single();
hbmProperty.name.Should().Be("something");
hbmProperty.access.Should().Be("field");
hbmProperty.length.Should().Be("150");
}
开发者ID:Ruhollah,项目名称:nhibernate-core,代码行数:32,代码来源:MappingOfPrivateMembersOnRootEntity.cs
示例6: PostProcessConfiguration
protected override void PostProcessConfiguration(global::NHibernate.Cfg.Configuration config)
{
base.PostProcessConfiguration(config);
if (FluentNhibernateMappingAssemblies != null)
{
// add any class mappings in the listed assemblies:
var mapper = new ModelMapper();
foreach (var asm in FluentNhibernateMappingAssemblies.Select(Assembly.Load))
{
mapper.AddMappings(asm.GetTypes());
}
foreach (var mapping in mapper.CompileMappingForEachExplicitlyAddedEntity())
{
config.AddMapping(mapping);
}
foreach (string assemblyName in FluentNhibernateMappingAssemblies)
{
config.AddMappingsFromAssembly(Assembly.Load(assemblyName));
}
}
}
开发者ID:ora11g,项目名称:NossonCore,代码行数:25,代码来源:FluentNHibernateLocalSessionFactoryObject.cs
示例7: GetMappings
protected override HbmMapping GetMappings()
{
var mapper = new ModelMapper();
mapper.Class<Order>(rc =>
{
rc.Table("Orders");
rc.Id(x => x.Id, m => m.Generator(Generators.GuidComb));
rc.Property(x => x.Name);
rc.Set(x => x.OrderLines, m =>
{
m.Inverse(true);
m.Key(k =>
{
k.Column("OrderId");
k.NotNullable(true);
});
m.Cascade(Mapping.ByCode.Cascade.All.Include(Mapping.ByCode.Cascade.DeleteOrphans));
m.Access(Accessor.NoSetter);
}, m => m.OneToMany());
});
mapper.Class<OrderLine>(rc =>
{
rc.Table("OrderLines");
rc.Id(x => x.Id, m => m.Generator(Generators.GuidComb));
rc.Property(x => x.Name);
rc.ManyToOne(x => x.Order, m => m.Column("OrderId"));
});
return mapper.CompileMappingForAllExplicitlyAddedEntities();
}
开发者ID:marchlud,项目名称:nhibernate-core,代码行数:30,代码来源:Fixture.cs
示例8: GetMapping
public static HbmMapping GetMapping()
{
var modelMapper = new ModelMapper();
modelMapper.AddMappings(Assembly.GetAssembly(typeof(PeopleMap)).GetExportedTypes());
HbmMapping mapping = modelMapper.CompileMappingForAllExplicitlyAddedEntities();
return mapping;
}
开发者ID:chenbojian,项目名称:cbjany,代码行数:7,代码来源:NhibernateCfg.cs
示例9: ShouldProperlyMapComponentWhenMappingOnlyPartOfItInSomePlaces
public void ShouldProperlyMapComponentWhenMappingOnlyPartOfItInSomePlaces()
{
var mapper = new ModelMapper();
mapper.Class<ClassWithComponents>(cm =>
{
cm.Component(x => x.Component1, c =>
{
c.Property(x => x.PropertyOne, p => p.Column("OnePropertyOne"));
});
cm.Component(x => x.Component2, c =>
{
c.Property(x => x.PropertyOne, p => p.Column("TwoPropertyOne"));
c.Property(x => x.PropertyTwo, p => p.Column("TwoPropertyTwo"));
});
});
//Compile, and get the component property in which we mapped only one inner property
var mappings = mapper.CompileMappingForAllExplicitlyAddedEntities();
var component1PropertyMapping = (HbmComponent)mappings.RootClasses[0].Properties.Single(x => x.Name == "Component1");
//There should be only one inner property in the mapping of this component
// Note: take a look at how CURRENTLY the test fails with 1 expected vs 2, instead of vs 3.
// This means that the "PropertyThree" property of the component that was never mapped, is not taken into account (which is fine).
Assert.That(component1PropertyMapping.Items.Length, Is.EqualTo(1));
}
开发者ID:marchlud,项目名称:nhibernate-core,代码行数:27,代码来源:FixtureByCode.cs
示例10: Setup
public void Setup()
{
var mapper = new ModelMapper();
mapper.AddMapping<OutboxEntityMap>();
var configuration = new global::NHibernate.Cfg.Configuration()
.AddProperties(new Dictionary<string, string>
{
{ "dialect", dialect },
{ global::NHibernate.Cfg.Environment.ConnectionString,connectionString }
});
configuration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
new SchemaUpdate(configuration).Execute(false, true);
SessionFactory = configuration.BuildSessionFactory();
Session = SessionFactory.OpenSession();
persister = new OutboxPersister
{
StorageSessionProvider = new FakeSessionProvider(SessionFactory, Session),
EndpointName = "TestEndpoint"
};
}
开发者ID:andrewq,项目名称:NServiceBus.NHibernate,代码行数:27,代码来源:InMemoryDBFixture.cs
示例11: NHibernateConfiguration
public static void NHibernateConfiguration(TestContext context)
{
log4net.Config.XmlConfigurator.Configure();
Configuration = new Configuration();
// lendo o arquivo hibernate.cfg.xml
Configuration.Configure();
FilterDefinition filterDef = new FilterDefinition(
"Empresa","EMPRESA = :EMPRESA",
new Dictionary<string, IType>() {{"EMPRESA", NHibernateUtil.Int32}}, false);
Configuration.AddFilterDefinition(filterDef);
filterDef = new FilterDefinition(
"Ativa", "ATIVO = 'Y'",
new Dictionary<string, IType>(), false);
Configuration.AddFilterDefinition(filterDef);
// Mapeamento por código
var mapper = new ModelMapper();
mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());
HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
Configuration.AddMapping(mapping);
// Gerar o XML a partir do mapeamento de codigo.
//var mappingXMl = mapping.AsString();
// Mapeamento por arquivo, in resource.
Configuration.AddAssembly(Assembly.GetExecutingAssembly());
// Gerando o SessionFactory
SessionFactory = Configuration.BuildSessionFactory();
}
开发者ID:hrickmachado,项目名称:Crowdlearning-Tecnologia-NHibernate,代码行数:32,代码来源:Context.cs
示例12: GetMappings
private HbmMapping GetMappings()
{
var mapper = new ModelMapper();
mapper.BeforeMapClass += (mi, t, map) => map.Id(x => x.Generator(Generators.GuidComb));
mapper.Class<Parent>(rc =>
{
rc.Id(p => p.Id);
rc.Property(p => p.ParentCode, m => m.Unique(true));
rc.Property(p => p.Name);
rc.Bag(p => p.Children, m =>
{
m.Key(km => { km.Column(cm => cm.Name("ParentParentCode")); km.PropertyRef(pg => pg.ParentCode); });
m.Inverse(true);
m.Cascade(Mapping.ByCode.Cascade.Persist);
}, rel => rel.OneToMany());
});
mapper.Class<Child>(rc =>
{
rc.Id(p => p.Id);
rc.Property(p => p.Name);
rc.ManyToOne<Parent>(p => p.Parent, m => { m.Column("ParentParentCode"); m.PropertyRef("ParentCode"); });
});
return mapper.CompileMappingForAllExplicitlyAddedEntities();
}
开发者ID:NikGovorov,项目名称:nhibernate-core,代码行数:28,代码来源:FixtureByCode.cs
示例13: SessionFactory
static SessionFactory()
{
var connectionString = @"Data Source=.\sqlexpress2014;Initial Catalog=BlogDatabase;Integrated Security=True";
var configuration = new Configuration();
configuration.DataBaseIntegration(
x =>
{
x.ConnectionString = connectionString;
x.Driver<SqlClientDriver>();
x.Dialect<MsSql2012Dialect>();
});
configuration.SetProperty(Environment.UseQueryCache, "true");
configuration.SetProperty(Environment.UseSecondLevelCache, "true");
configuration.SetProperty(Environment.CacheProvider, typeof(SysCacheProvider).AssemblyQualifiedName);
var mapper = new ModelMapper();
mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());
mapper.BeforeMapBag += (modelInspector, member1, propertyCustomizer) =>
{
propertyCustomizer.Inverse(true);
propertyCustomizer.Cascade(Cascade.All | Cascade.DeleteOrphans);
};
mapper.BeforeMapManyToOne +=
(modelInspector, member1, propertyCustomizer) => { propertyCustomizer.NotNullable(true); };
mapper.BeforeMapProperty += (inspector, member, customizer) => customizer.NotNullable(true);
var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
configuration.AddMapping(mapping);
sessionFactory = configuration.BuildSessionFactory();
}
开发者ID:Nerielle,项目名称:Learning,代码行数:30,代码来源:SessionFactory.cs
示例14: AddFromConfig
private static void AddFromConfig(ModelMapper modelMapper, IList<Assembly> assemblies)
{
for (int i = 0; i < assemblies.Count; ++i)
{
modelMapper.AddMappings(assemblies[i].GetTypes());
}
}
开发者ID:michelelepri,项目名称:NHibernate.LoquaciousMappingConfig,代码行数:7,代码来源:ModelMapperExtend.cs
示例15: AzureSubcriptionStorage
/// <summary>
/// Configures the storage with the user supplied persistence configuration
/// Azure tables are created if requested by the user
/// </summary>
/// <param name="config"></param>
/// <param name="connectionString"></param>
/// <param name="createSchema"></param>
/// <returns></returns>
public static Configure AzureSubcriptionStorage(this Configure config,
string connectionString,
bool createSchema,
string tableName)
{
var cfg = new Configuration()
.DataBaseIntegration(x =>
{
x.ConnectionString = connectionString;
x.ConnectionProvider<TableStorageConnectionProvider>();
x.Dialect<TableStorageDialect>();
x.Driver<TableStorageDriver>();
});
SubscriptionMap.TableName = tableName;
var mapper = new ModelMapper();
mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());
var faultMappings = mapper.CompileMappingForAllExplicitlyAddedEntities();
cfg.AddMapping(faultMappings);
if (createSchema)
{
new SchemaExport(cfg).Execute(true, true, false);
}
var sessionSource = new SubscriptionStorageSessionProvider(cfg.BuildSessionFactory());
config.Configurer.RegisterSingleton<ISubscriptionStorageSessionProvider>(sessionSource);
config.Configurer.ConfigureComponent<SubscriptionStorage>(DependencyLifecycle.InstancePerCall);
return config;
}
开发者ID:remogloor,项目名称:NServiceBus,代码行数:43,代码来源:ConfigureNHibernateAzureSubscriptionStorage.cs
示例16: CreateModelMapper
ModelMapper CreateModelMapper()
{
var mapper = new ModelMapper();
mapper.AfterMapClass += (inspector, type, customizer) =>
{
// make sure that sagas are assigned for the Id, or bad things happen
if (typeof(ISaga).IsAssignableFrom(type))
customizer.Id(m => m.Generator(Generators.Assigned));
};
mapper.AfterMapProperty += (inspector, member, customizer) =>
{
Type memberType = member.LocalMember.GetPropertyOrFieldType();
if (memberType.IsGenericType
&& typeof(Nullable<>).IsAssignableFrom(memberType.GetGenericTypeDefinition()))
{
customizer.NotNullable(false);
}
else if (!typeof(string).IsAssignableFrom(memberType))
{
customizer.NotNullable(true);
}
};
mapper.AddMappings(_mappedTypes);
return mapper;
}
开发者ID:cstick,项目名称:MassTransit,代码行数:30,代码来源:NHibernateSessionFactoryProvider.cs
示例17: Customize
private static void Customize(ModelMapper mapper)
{
mapper.Class<EntityBase>(map =>
{
map.Id(e => e.Id, id => id.Generator(Generators.HighLow));
map.Version(e => e.Version, d => { });
});
mapper.Class<Product>(map => map.Set(p => p.Customizations,
set => set.Cascade(Cascade.All),
rel => rel.ManyToMany()));
mapper.Class<Customization>(map => map.Set(p => p.PossibleValues,
set => set.Cascade(Cascade.All),
rel => rel.Element()));
mapper.Class<Order>(map =>
{
map.Set(p => p.Items, set =>
{
set.Cascade(Cascade.All);
set.Inverse(true);
});
map.ManyToOne(o => o.Payment, o => o.Cascade(Cascade.All));
});
}
开发者ID:horsdal,项目名称:Restbucks-on-Nancy,代码行数:25,代码来源:Mapper.cs
示例18: GetMappings
protected override HbmMapping GetMappings()
{
// The impl/mapping of the bidirectional one-to-many sucks but was provided as is
var mapper = new ModelMapper();
mapper.BeforeMapClass += (i, t, cm) => cm.Id(map =>
{
map.Column((t.Name + "Id").ToUpperInvariant());
map.Generator(Generators.HighLow, g => g.Params(new { max_lo = "1000" }));
});
mapper.Class<Customer>(ca =>
{
ca.Lazy(false);
ca.Id(x => x.Id, m => { });
ca.NaturalId(x => x.Property(c => c.Name, p => p.NotNullable(true)));
ca.Property(x => x.Address, p => p.Lazy(true));
ca.Set(c => c.Orders, c =>
{
c.Key(x => x.Column("CUSTOMERID"));
c.Inverse(true);
c.Cascade(Mapping.ByCode.Cascade.All);
}, c => c.OneToMany());
});
mapper.Class<Order>(cm =>
{
cm.Id(x => x.Id, m => { });
cm.Property(x => x.Date);
cm.ManyToOne(x => x.Customer, map => map.Column("CUSTOMERID"));
});
return mapper.CompileMappingForAllExplicitlyAddedEntities();
}
开发者ID:Ruhollah,项目名称:nhibernate-core,代码行数:30,代码来源:Fixture.cs
示例19: GetMapper
private static ModelMapper GetMapper()
{
var mapper = new ModelMapper();
mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());
return mapper;
}
开发者ID:SergerGood,项目名称:OrderSample,代码行数:7,代码来源:SessionFactory.cs
示例20: TestMapElementElement
public void TestMapElementElement()
{
var mapper = new ModelMapper();
mapper.Class<ClassWithMapElementElement>(
c =>
{
c.Lazy(false);
c.Id(id => id.Id, id => id.Generator(Generators.Identity));
c.Map(
m => m.Map,
col =>
{
col.Table("element_element");
col.Key(k => k.Column("id"));
},
key => key.Element(e => e.Column("key")),
element => element.Element(e => e.Column("element")));
});
var mappings = mapper.CompileMappingForAllExplicitlyAddedEntities();
var hbmClass = mappings.RootClasses.FirstOrDefault(c => c.Name == typeof (ClassWithMapElementElement).Name);
var hbmMap = hbmClass.Properties.OfType<HbmMap>().SingleOrDefault();
Assert.That(hbmMap, Is.Not.Null);
Assert.That(hbmMap.Item, Is.TypeOf<HbmMapKey>());
Assert.That(hbmMap.Item1, Is.TypeOf<HbmElement>());
}
开发者ID:marchlud,项目名称:nhibernate-core,代码行数:29,代码来源:MapFixture.cs
注:本文中的ModelMapper类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论