本文整理汇总了C#中Mapper类的典型用法代码示例。如果您正苦于以下问题:C# Mapper类的具体用法?C# Mapper怎么用?C# Mapper使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Mapper类属于命名空间,在下文中一共展示了Mapper类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: CreateMapping
public HbmMapping CreateMapping()
{
var orm = new ObjectRelationalMapper();
//主键生成策略(自增)
orm.Patterns.PoidStrategies.Add(new NativePoidPattern());
var entities = new[]
{
typeof(User),
typeof(PlusMaterial),
typeof(StockIn),
typeof(StockInDetail),
typeof(StockOut),
typeof(StockOutDetail),
};
orm.TablePerClass(entities);
//关系映射
orm.ManyToOne<StockInDetail, StockIn>();
orm.ManyToOne<StockOutDetail, StockOut>();
//数据库命名规则
var mapper = new Mapper(orm, new CoolPatternsAppliersHolder(orm));
orm.TablePerClass(entities);
var hc = mapper.CompileMappingFor(Assembly.Load("PMMS.Entities").GetTypes());
return hc;
}
开发者ID:henleygao,项目名称:PMMS,代码行数:27,代码来源:MappingFactory.cs
示例2: CustomizeRelations
private void CustomizeRelations(Mapper mapper)
{
/* TODO: add IDomainInspector.IsOptionalOneToMany to avoid auto OnDelete.Cascade and soft-Cascade actions.
IsOptionalOneToMany may come in place using Declared.Explicit in the ORM */
mapper.Class<User>(cm =>
{
cm.Id(u => u.Id, im => im.Generator(Generators.Foreign<User>(u => u.Human)));
cm.OneToOne(u => u.Human, otom => otom.Constrained(true));
});
mapper.Class<Human>(cm => cm.Bag(human => human.Pets, bagm =>
{
bagm.Cascade(Cascade.None);
bagm.Key(km => km.OnDelete(OnDeleteAction.NoAction));
}, cer => { }));
mapper.Class<Zoo>(cm =>
{
cm.Map(zoo => zoo.Mammals, mapm =>
{
mapm.Cascade(Cascade.None);
mapm.Key(km => km.OnDelete(OnDeleteAction.NoAction));
mapm.Inverse(false);
}, x=> { }, cer => { });
cm.Map(zoo => zoo.Animals, mapm =>
{
mapm.Cascade(Cascade.None);
mapm.Key(km => km.OnDelete(OnDeleteAction.NoAction));
}, x => { }, cer => { });
});
}
开发者ID:alvarezdaniel,项目名称:conformando-nhibernate,代码行数:29,代码来源:NaturalnessModuleMapping.cs
示例3: Map_ShouldMapReportNumber
public void Map_ShouldMapReportNumber()
{
//Arrange
var mapper = new Mapper<INV_DIAMONDS_INVENTORY>(Igal.ConversionDictionary);
var igalDiamond = new Igal()
{
Clarity = "SI2",
Culet = "",
Color = "H",
Cut = "VG",
DepthPresentage = (decimal)4.25,
InventoryCode = "12345",
Fluorescence = "MB",
Girdle = "",
Length = (decimal)3.5,
Polish = "G",
Price = 9999,
Report = "EGL IL",
ReportURL = "",
Shape = "BR",
Symmetry = "EX",
Table = (decimal)54.5,
Weight = (decimal)2.41,
Width = (decimal)6.35,
ReportNumber = "123"
};
//Act
var inv_entry = mapper.Map(igalDiamond);
//Assert
inv_entry.report_number.Should().Be("123");
}
开发者ID:mamluka,项目名称:JewelryONet,代码行数:32,代码来源:MapperTests.cs
示例4: MapCollection_WhenConversionFailed_ShouldCorrectlyAddIndexToPathes
public void MapCollection_WhenConversionFailed_ShouldCorrectlyAddIndexToPathes()
{
// Arrange
var mapper = new Mapper<AContainer, BContainer>()
.Map((e, i) => e.Data[i].Name, (container, i) => container.Set[i].Numeric);
var left = fixture.CreateMany<AContainer>(15).ToList();
left.ForEach(e => e.Data.ForEach(d => d.Name = "124"));
left[11].Data[2] = new A { Name = "Error" };
// Throws
try
{
mapper.MapCollection(left);
Assert.True(false);
}
catch (ConversionException ex)
{
Assert.Equal(1, ex.Errors.Length);
var error = ex.Errors[0];
Assert.Equal("[11].Data[2].Name", error.SourcePath);
Assert.Equal("[11].Set[2].Numeric", error.DestinationPath);
Assert.NotEmpty(error.ErrorMessage);
Assert.Equal("Error", error.SourceValue);
}
}
开发者ID:rd-dev-ukraine,项目名称:two-way-mapper,代码行数:29,代码来源:MapCollectionTest.cs
示例5: BoolPropertyZeroIsParsedAsFalse
public void BoolPropertyZeroIsParsedAsFalse()
{
string input = "<TestClass BoolProp=\"0\" /> ";
var mapper = new Mapper<TestClass>(input);
TestClass result = mapper.ParseNext();
Assert.IsFalse(result.BoolProp);
}
开发者ID:qusma,项目名称:NXmlMapper,代码行数:7,代码来源:NXmlMapperTests.cs
示例6: InitMappings
/// <summary>
/// Initializes the mappings.
/// </summary>
/// <param name="config">The configuration.</param>
public static void InitMappings(Configuration config)
{
var orm = new ObjectRelationalMapper();
var mapper = new Mapper(orm);
mapper.AddPropertyPattern(mi => mi.GetPropertyOrFieldType() == typeof(string) && !mi.Name.EndsWith("Text"), pm => pm.Length(50));
mapper.AddPropertyPattern(mi => mi.GetPropertyOrFieldType() == typeof(string) && mi.Name.EndsWith("Text"), pm => pm.Type(NHibernateUtil.StringClob));
orm.Patterns.PoidStrategies.Add(new AssignedPoidPattern());
foreach (var componentDbInit in IoC.ResolveAllInstances<IComponentDbInit>())
{
componentDbInit.InitMappings(orm, mapper);
}
// compile the mapping for the specified entities
HbmMapping mappingDocument = mapper.CompileMappingFor(ListOfModelTypes());
// inject the mapping in NHibernate
config.AddDeserializedMapping(mappingDocument, "Domain");
// fix up the schema
SchemaMetadataUpdater.QuoteTableAndColumns(config);
SessionFactory.SessionFactoryInstance = config.BuildSessionFactory();
}
开发者ID:GunioRobot,项目名称:vlko,代码行数:30,代码来源:DBInit.cs
示例7: BuildMapper
public virtual IMapper BuildMapper()
{
if (mapper != null)
{
// log
Settings.InfoLog.Invoke(MethodBase.GetCurrentMethod().Name + " Invoked more than once. Returning cached instance! Make sure you do not call this method multiple times.");
}
else
{
var mapperLocal = new Mapper(Settings.MappingStrategyBuilder = Settings.MappingStrategyBuilder ?? BuildMappingStrategyBuilder(),
Settings.MappingCompiler = Settings.MappingCompiler ?? BuildMappingCompiler(),
Settings.TypeMatchers = Settings.TypeMatchers ?? BuildTypeMatchers());
var mappings = new List<MappingInfo>();
var bag = new MappingBag(mappings);
foreach (var catalog in catalogs)
{
catalog.Collect(bag);
}
mappings.Sort();
foreach (var mapping in mappings)
{
mapperLocal.RegisterMapping(mapping);
}
mapper = mapperLocal;
}
return mapper;
}
开发者ID:olcayseker,项目名称:Cartographer,代码行数:27,代码来源:MapperBuilder.cs
示例8: ComposingPatternsAppliersPacks
public void ComposingPatternsAppliersPacks()
{
// Thanks to Lorenzo Vegetti to provide the domain of this example.
// This example refers to a little-domain, interesting from the point of view of mapping with ConfORM.
// Here you can see how apply general convetion, how and when compose patterns-appliers-packs and patterns-appliers,
// how ConfORM can apply different mapping depending on the type of enum (see the difference on CostOptions) and so on...
// You don't have to organize the mapping all in one class, as in this example, and you don't have to use the IModuleMapping...
// You can organize the mapping as you feel more confortable for your application; in some case a class is enough, in other cases would
// be better the separation per module/concern, you are not closed in "mapping per class" box.
var orm = new ObjectRelationalMapper();
// With the follow line I'm adding the pattern for the POID strategy ("native" instead the default "High-Low")
orm.Patterns.PoidStrategies.Add(new NativePoidPattern());
// composition of patterns-appliers-packs and patterns-appliers for Lorenzo's domain
// Note: for bidirectional-one-to-many association Lorenzo is not interested in the default cascade behavior,
// implemented in the BidirectionalOneToManyRelationPack, because he is using a sort of soft-delete in his base class VersionModelBase.
// He can implements a custom pack of patterns-appliers to manage the situation when classes does not inherits from VersionModelBase by the way
// he don't want the cascade atall, so the BidirectionalOneToManyInverseApplier will be enough
IPatternsAppliersHolder patternsAppliers =
(new SafePropertyAccessorPack())
.Merge(new OneToOneRelationPack(orm))
.Merge(new BidirectionalManyToManyRelationPack(orm))
.Merge(new DiscriminatorValueAsClassNamePack(orm))
.Merge(new CoolColumnsNamingPack(orm))
.Merge(new TablePerClassPack())
.Merge(new PluralizedTablesPack(orm, new EnglishInflector()))
.Merge(new ListIndexAsPropertyPosColumnNameApplier())
.Merge(new BidirectionalOneToManyInverseApplier(orm))
.Merge(new EnumAsStringPack())
.Merge(new DatePropertyByNameApplier())
.Merge(new MsSQL2008DateTimeApplier());
// Instancing the Mapper using the result of Merge
var mapper = new Mapper(orm, patternsAppliers);
// Setting the version property using the base class
orm.VersionProperty<VersionModelBase>(v => v.Version);
// Note: I'm declaring the strategy only for the base entity
orm.TablePerClassHierarchy<Cost>();
orm.TablePerClass<EditionQuotation>();
orm.TablePerClass<ProductQuotation>();
orm.TablePerClass<Quotation>();
AppliesGeneralConventions(mapper);
// EditionQuotation.PrintCost don't use lazy-loading
mapper.Customize<EditionQuotation>(map => map.ManyToOne(eq => eq.PrintCost, m2o => m2o.Lazy(LazyRelation.NoLazy)));
// Customizes some others DDL's stuff outside conventions
CustomizeColumns(mapper);
// Note : I have to create mappings for the whole domain
HbmMapping mapping =
mapper.CompileMappingFor(
typeof (GenericModelBase<>).Assembly.GetTypes().Where(t => t.Namespace == typeof (GenericModelBase<>).Namespace));
Console.Write(mapping.AsString());
}
开发者ID:alvarezdaniel,项目名称:conformando-nhibernate,代码行数:60,代码来源:Demo.cs
示例9: WhenCustomizedAndSpecifiedThenSetDifferentConfigurationForSameComponent
public void WhenCustomizedAndSpecifiedThenSetDifferentConfigurationForSameComponent()
{
Mock<IDomainInspector> orm = GetMockedDomainInspector();
var domainInspector = orm.Object;
var mapper = new Mapper(domainInspector);
mapper.Customize<Name>(name =>
{
name.Property(np => np.First, pm => pm.Length(20));
name.Property(np => np.Last, pm => pm.Length(35));
});
mapper.Class<Person>(c =>
{
c.Component(p => p.RealName, cname => cname.Property(cnp => cnp.Last, pm => pm.Length(50)));
c.Component(p => p.Aka, cname => cname.Property(cnp => cnp.First, pm => pm.Length(50)));
});
HbmMapping mapping = mapper.CompileMappingFor(new[] { typeof(Person) });
HbmClass rc = mapping.RootClasses.First(r => r.Name.Contains("Person"));
var hbmRealName = (HbmComponent)rc.Properties.First(p => p.Name == "RealName");
var hbmAka = (HbmComponent)rc.Properties.First(p => p.Name == "Aka");
hbmRealName.Properties.OfType<HbmProperty>().Select(p => p.length).Should().Have.SameValuesAs("20", "50");
hbmAka.Properties.OfType<HbmProperty>().Select(p => p.length).Should().Have.SameValuesAs("50", "35");
}
开发者ID:alvarezdaniel,项目名称:conformando-nhibernate,代码行数:26,代码来源:ComponentDoublePropertyTest.cs
示例10: Add
/// <summary>
/// Adds a mapper for the specified token
/// </summary>
public void Add(string token, Mapper mapper)
{
if(token==null) throw new ArgumentNullException("token is null");
if(mapper==null) throw new ArgumentNullException("mapper is null");
m_Mappers[token]=mapper;
}
开发者ID:BrianGoff,项目名称:BITS,代码行数:10,代码来源:TokenExpander.cs
示例11: TransposeRegroupsPerTargetRepositoryAndBranch
public void TransposeRegroupsPerTargetRepositoryAndBranch()
{
var m = new Mapper()
.Add(new Parts("o1/r1", TreeEntryTargetType.Blob, "b1", "a"),
new Parts("o1/r2", TreeEntryTargetType.Blob, "b1", "a"),
new Parts("o1/r2", TreeEntryTargetType.Blob, "b1", "b"),
new Parts("o1/r3", TreeEntryTargetType.Blob, "b1", "a"))
.Add(new Parts("o1/r1", TreeEntryTargetType.Tree, "b1", "t1"),
new Parts("o1/r2", TreeEntryTargetType.Tree, "b1", "t"))
.Add(new Parts("o2/r4", TreeEntryTargetType.Tree, "b3", "t3"),
new Parts("o1/r3", TreeEntryTargetType.Tree, "b1", "sub/t"),
new Parts("o1/r2", TreeEntryTargetType.Tree, "b1", "t2"))
.Add(new Parts("o1/r1", TreeEntryTargetType.Tree, "b1", "t2"),
new Parts("o1/r2", TreeEntryTargetType.Tree, "b2", "t"),
new Parts("o1/r3", TreeEntryTargetType.Tree, "b1", "t"));
var t = m.Transpose();
var orbs = t.Keys.ToList();
orbs.Sort(StringComparer.Ordinal);
Assert.AreEqual(new[]
{
"o1/r2/b1",
"o1/r2/b2",
"o1/r3/b1"
}, orbs.ToArray());
}
开发者ID:synhershko,项目名称:SyncOMatic,代码行数:28,代码来源:MapperFixture.cs
示例12: PocoMapperTests
public PocoMapperTests(ITestOutputHelper x)
{
x.Logger();
LogManager.OutputToTrace();
_sut = Setup.MapperFactory().CreateMapper<MapperPost>("1") as Mapper<MapperPost>;
}
开发者ID:sapiens,项目名称:SqlFu,代码行数:7,代码来源:PocoMapperTests.cs
示例13: ExecuteCustomDelegatedApplier
public void ExecuteCustomDelegatedApplier()
{
var orm = new Mock<IDomainInspector>();
orm.Setup(m => m.IsEntity(It.IsAny<Type>())).Returns(true);
orm.Setup(m => m.IsRootEntity(It.IsAny<Type>())).Returns(true);
orm.Setup(m => m.IsTablePerClass(It.IsAny<Type>())).Returns(true);
orm.Setup(m => m.IsPersistentId(It.Is<MemberInfo>(mi => mi.Name == "Id"))).Returns(true);
orm.Setup(m => m.IsPersistentProperty(It.Is<MemberInfo>(mi => mi.Name != "Id"))).Returns(true);
var mapper = new Mapper(orm.Object);
mapper.AddPropertyPattern(mi => mi.GetPropertyOrFieldType() == typeof(DateTime) && (mi.Name.StartsWith("Date") || mi.Name.EndsWith("Date")),
pm => pm.Type(NHibernateUtil.Date));
var mapping = mapper.CompileMappingFor(new[] {typeof (MyClass)});
var hbmClass = mapping.RootClasses.Single();
var hbmProp = (HbmProperty) hbmClass.Properties.First(p => p.Name == "Date");
hbmProp.Type.name.Should().Be.EqualTo("Date");
hbmProp = (HbmProperty)hbmClass.Properties.First(p => p.Name == "DateOfMeeting");
hbmProp.Type.name.Should().Be.EqualTo("Date");
hbmProp = (HbmProperty)hbmClass.Properties.First(p => p.Name == "MeetingDate");
hbmProp.Type.name.Should().Be.EqualTo("Date");
hbmProp = (HbmProperty)hbmClass.Properties.First(p => p.Name == "StartAt");
hbmProp.Type.Should().Be.Null();
}
开发者ID:alvarezdaniel,项目名称:conformando-nhibernate,代码行数:28,代码来源:CustomPropertyPatternApplierTest.cs
示例14: ParseAndSave
public void ParseAndSave()
{
var file = httpContext.Request.Files[0];
IEnumerable<ISupplier> list = null;
Dictionary<string, Dictionary<string, int>> ConversionDictionary = null;
switch (model.Supplier)
{
case "Igal":
list = csvParser.Parse<Igal>(file.InputStream);
ConversionDictionary = Igal.ConversionDictionary;
break;
case "IgalGIA":
list = csvParser.Parse<IgalGIA>(file.InputStream);
ConversionDictionary = IgalGIA.ConversionDictionary;
break;
}
list = list.Distinct().ToList();
var mapper = new Mapper<INV_DIAMONDS_INVENTORY>(ConversionDictionary);
mapper.SetPricePolicy(PricePolicy.Calibrate);
mapper.OurPriceCalibration((decimal)1.07);
var dblist = list.Select(mapper.Map).ToList();
var db = new DatabasePersistence();
db.AddSupplierDiamondList(dblist);
db.SaveOrUpdate();
}
开发者ID:mamluka,项目名称:JewelryONet,代码行数:32,代码来源:TempUpdateDiamodsHendler.cs
示例15: GetMapping
private static HbmMapping GetMapping()
{
var orm = new ObjectRelationalMapper();
var mapper = new Mapper(orm,
new CoolPatternsAppliersHolder(orm));
orm.TablePerClassHierarchy<Product>();
orm.TablePerClass<ActorRole>();
orm.Patterns.PoidStrategies.Add(
new GuidOptimizedPoidPattern());
orm.VersionProperty<Entity>(x => x.Version);
orm.NaturalId<Product>(p => p.Name);
orm.Cascade<Movie, ActorRole>(
Cascade.All | Cascade.DeleteOrphans);
mapper.AddPropertyPattern(mi =>
mi.GetPropertyOrFieldType() == typeof(Decimal) &&
mi.Name.Contains("Price"),
pm => pm.Type(NHibernateUtil.Currency));
mapper.AddPropertyPattern(mi =>
orm.IsRootEntity(mi.DeclaringType) &&
!"Description".Equals(mi.Name),
pm => pm.NotNullable(true));
mapper.Subclass<Movie>(cm =>
cm.List(movie => movie.Actors,
colm => colm.Index(
lim => lim.Column("ActorIndex")), m => { }));
var domainClasses = typeof(Entity).Assembly.GetTypes()
.Where(t => typeof(Entity).IsAssignableFrom(t));
return mapper.CompileMappingFor(domainClasses);
}
开发者ID:dinhqbao,项目名称:NHibernate-3.0-Cookbook,代码行数:29,代码来源:Program.cs
示例16: StripeService
public StripeService(string apiKey = null)
{
ApiKey = apiKey;
Mapper = new Mapper();
Requestor = new Requestor(Mapper);
ParameterBuilder = new ParameterBuilder();
}
开发者ID:nkohari,项目名称:stripe.net,代码行数:7,代码来源:StripeService.cs
示例17: GetMapings
public static HbmMapping GetMapings(ObjectRelationalMapper orm)
{
domainEntities =
typeof(Entity).Assembly.GetTypes()
.Where(t => typeof(Entity).IsAssignableFrom(t) && !t.IsGenericType)
.ToList();
orm.Cascade<Claim, CPS.Domain.Action>(CascadeOn.None);
orm.Cascade<Branch, Claim>(CascadeOn.None);
orm.Cascade<Domain.Action,Document>(CascadeOn.All);
orm.Component<Address>();
orm.Component<Incident>();
orm.Component<ContactInfo>();
var patterns = new SafePropertyAccessorPack().Merge(new OneToOneRelationPack(orm))
.Merge(new BidirectionalManyToManyRelationPack(orm))
.Merge(new BidirectionalOneToManyRelationPack(orm))
.Merge(new DiscriminatorValueAsClassNamePack(orm))
.Merge(new CoolColumnsNamingPack(orm))
.Merge(new TablePerClassPack())
.Merge(new ListIndexAsPropertyPosColumnNameApplier())
.Merge(new PluralizedTablesPack(orm, new EnglishInflector()))
.Merge(new MsSQL2008DateTimeApplier());
var mapper = new Mapper(orm, patterns);
var mapping = mapper.CompileMappingFor(domainEntities);
Debug.WriteLine(mapping.AsString());
return mapping;
}
开发者ID:RoyRV,项目名称:Training.MVC.Net,代码行数:32,代码来源:MapConfiguration.cs
示例18: BoolPropertyTrueStringIsParsedAsTrue
public void BoolPropertyTrueStringIsParsedAsTrue()
{
string input = "<TestClass BoolProp=\"true\" /> ";
var mapper = new Mapper<TestClass>(input);
TestClass result = mapper.ParseNext();
Assert.IsTrue(result.BoolProp);
}
开发者ID:qusma,项目名称:NXmlMapper,代码行数:7,代码来源:NXmlMapperTests.cs
示例19: Import
public Import(ILocalhost localhost, IGenerator generator)
{
this.localhost = localhost;
this.generator = generator;
mapper = new Mapper<Key, Key>();
interactions = new List<Interaction>();
}
开发者ID:raysearchlabs,项目名称:spark,代码行数:7,代码来源:Import.cs
示例20: CallCustomizerOnCompositeElementsProperties
public void CallCustomizerOnCompositeElementsProperties()
{
Mock<IDomainInspector> orm = GetMockedDomainInspector();
var mapper = new Mapper(orm.Object);
bool simplePropertyCalled = false;
bool manyToOneCalled = false;
bool reSimplePropertyCalled = false;
bool reManyToOneCalled = false;
mapper.Customize<MyComponent>(x =>
{
x.Property(mc => mc.Simple, pm => simplePropertyCalled = true);
x.ManyToOne(mc => mc.ManyToOne, pm => manyToOneCalled = true);
});
mapper.Customize<MyNestedComponent>(x =>
{
x.Property(mc => mc.ReSimple, pm => reSimplePropertyCalled = true);
x.ManyToOne(mc => mc.ReManyToOne, pm => reManyToOneCalled = true);
});
mapper.CompileMappingFor(new[] { typeof(MyClass) });
simplePropertyCalled.Should().Be.True();
manyToOneCalled.Should().Be.True();
reSimplePropertyCalled.Should().Be.True();
reManyToOneCalled.Should().Be.True();
}
开发者ID:alvarezdaniel,项目名称:conformando-nhibernate,代码行数:26,代码来源:CustomizerCallingOnCompositeElementTest.cs
注:本文中的Mapper类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论