本文整理汇总了C#中Mapper类的典型用法代码示例。如果您正苦于以下问题:C# Mapper类的具体用法?C# Mapper怎么用?C# Mapper使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Mapper类属于命名空间,在下文中一共展示了Mapper类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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;
}
示例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 => { });
});
}
示例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");
}
示例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);
}
}
示例5: BoolPropertyZeroIsParsedAsFalse
public void BoolPropertyZeroIsParsedAsFalse()
{
string input = "<TestClass BoolProp=\"0\" /> ";
var mapper = new Mapper<TestClass>(input);
TestClass result = mapper.ParseNext();
Assert.IsFalse(result.BoolProp);
}
示例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();
}
示例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;
}
示例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());
}
示例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");
}
示例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;
}
示例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());
}
示例12: PocoMapperTests
public PocoMapperTests(ITestOutputHelper x)
{
x.Logger();
LogManager.OutputToTrace();
_sut = Setup.MapperFactory().CreateMapper<MapperPost>("1") as Mapper<MapperPost>;
}
示例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();
}
示例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();
}
示例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);
}