Search Results

Search found 99 results on 4 pages for 'automapper'.

Page 2/4 | < Previous Page | 1 2 3 4  | Next Page >

  • AutoMapper : Site wide usage of IValueFormatter for given types

    - by CRice
    It is my understanding I can configure AutoMapper in the following way and during mapping it should format all source model dates to the rules defined in the IValueFormatter and set the result to the mapped model. ForSourceType<DateTime>().AddFormatter<StandardDateFormatter>(); ForSourceType<DateTime?>().AddFormatter<StandardDateFormatter>(); I get no effect for my mapped class with this. It only works when I do the following: Mapper.CreateMap<Member, MemberForm>().ForMember(x => x.DateOfBirth, y => y.AddFormatter<StandardDateFormatter>()); I am mapping DateTime? Member.DateOfBirth to string MemberForm.DateOfBirth. The formatter basically creates a short date string from the date. Is there something I am missing when setting the default formatter for a given type? Thanks public class StandardDateFormatter : IValueFormatter { public string FormatValue(ResolutionContext context) { if (context.SourceValue == null) return null; if (!(context.SourceValue is DateTime)) return context.SourceValue.ToNullSafeString(); return ((DateTime)context.SourceValue).ToShortDateString(); } }

    Read the article

  • AutoMapper strings to enum descriptions

    - by 6footunder
    Given the requirement: Take an object graph, set all enum type properties based on the processed value of a second string property. Convention dictates that the name of the source string property will be that of the enum property with a postfix of "Raw". By processed we mean we'll need to strip specified characters e.t.c. I've looked at custom formatters, value resolvers and type converters, none of which seems like a solution for this? We want to use AutoMapper as opposed to our own reflection routine for two reasons, a) it's used extensively throughout the rest of the project and b) it gives you recursive traversal ootb. -- Example -- Given the (simple) structure below, and this: var tmp = new SimpleClass { CountryRaw = "United States", Person = new Person { GenderRaw="Male" } }; var tmp2 = new SimpleClass(); Mapper.Map(tmp, tmp2); we'd expect tmp2's MappedCountry enum to be Country.UnitedStates and the Person property to have a gender of Gender.Male. public class SimpleClass1 { public string CountryRaw {get;set;} public Country MappedCountry {get;set;} public Person Person {get;set;} } public class Person { public string GenderRaw {get;set;} public Gender Gender {get;set;} public string Surname {get;set;} } public enum Country { UnitedStates = 1, NewZealand = 2 } public enum Gender { Male, Female, Unknown } Thanks

    Read the article

  • AutoMapper recursive

    - by fra
    Hi! I would like to make a deep copy of a complex object tree using AutoMapper. The problem is that for each member I would like to construct a new object and then map it, and not simply copying the existing one. Here it is an example: public abstract class Test { public Test() { this.Id = Guid.NewGuid(); } public Guid Id { get; private set; } } public class OuterTest : Test { public InnerTest Inner { get; set; } } public class InnerTest : Test { public int Value { get; set; } } and how to test it: OuterTest outerDest = Mapper.Map<OuterTest, OuterTest>(outerSource); System.Diagnostics.Debug.WriteLine("InnerSource id: " + innerSource.Id); System.Diagnostics.Debug.WriteLine("InnerSource value: " + innerSource.Value); System.Diagnostics.Debug.WriteLine("OuterSource id: " + outerSource.Id); System.Diagnostics.Debug.WriteLine("OuterDest id: " + outerDest.Id); System.Diagnostics.Debug.WriteLine("OuterDest.Inner id: " + outerDest.Inner.Id); System.Diagnostics.Debug.WriteLine("OuterDest.Inner value: " + outerDest.Inner.Value); This is the result from the output window: InnerSource id: a60fda37-206a-40a8-a7f8-db480149c906 InnerSource value: 2119686684 OuterSource id: 7486899e-2da8-4873-9160-d6096b555c73 OuterDest id: 7486899e-2da8-4873-9160-d6096b555c73 OuterDest.Inner id: a60fda37-206a-40a8-a7f8-db480149c906 OuterDest.Inner value: 2119686684 The problem is thet the object innerSource is always the same instance as outerDest.Inner (I verified through MakeObjectId of VS debugger) but I would like them to be two different instances. How could I create a recursive map with this behavior? I tried creating a custom IValueResolver like the following, without success. public class AutoMapperNewObjectResolver : IValueResolver { public ResolutionResult Resolve(ResolutionResult source) { object resolved; if (source.Value != null) { object instance = Activator.CreateInstance(source.MemberType); resolved = Mapper.Map(source.Value, instance, source.MemberType, source.MemberType); } else { resolved = null; } ResolutionResult result = source.New(resolved, source.Context.DestinationType); return result; } } and configured like this: Mapper.CreateMap<OuterTest, OuterTest>() .ForMember(d => d.Inner, o => o.ResolveUsing<AutoMapperNewObjectResolver>().FromMember(src => src.Inner)); Any help appreciated, thank you

    Read the article

  • AutoMapper

    AutoMapper is an object-object mapper which allows you to solve issues with mapping the same properties from one object of one type to another object of another type. For example, mapping a heavy entity Customer object to the CustomerDTO could be done with AutoMapper automatically.

    Read the article

  • Simple Convention Automapper for two-way Mapping (Entities to/from ViewModels)

    - by Omu
    UPDATE: this stuff has evolved into a nice project, see it at http://valueinjecter.codeplex.com check this out, I just wrote a simple automapper, it takes the value from the property with the same name and type of one object and puts it into another, and you can add exceptions (ifs, switch) for each type you may need so tell me what do you think about it ? I did it so I could do something like this: Product –> ProductDTO ProductDTO –> Product that's how it begun: I use the "object" type in my Inputs/Dto/ViewModels for DropDowns because I send to the html a IEnumerable<SelectListItem> and I receive a string array of selected keys back public void Map(object a, object b) { var pp = a.GetType().GetProperties(); foreach (var pa in pp) { var value = pa.GetValue(a, null); // property with the same name in b var pb = b.GetType().GetProperty(pa.Name); if (pb == null) { //no such property in b continue; } if (pa.PropertyType == pb.PropertyType) { pb.SetValue(b, value, null); } } } UPDATE: the real usage: the Build methods (Input = Dto): public static TI BuildInput<TI, T>(this T entity) where TI: class, new() { var input = new TI(); input = Map(entity, input) as TI; return input; } public static T BuildEntity<T, TI, TR>(this TI input) where T : class, new() where TR : IBaseAdvanceService<T> { var id = (long)input.GetType().GetProperty("Id").GetValue(input, null); var entity = LocatorConfigurator.Resolve<TR>().Get(id) ?? new T(); entity = Map(input, entity) as T; return entity; } public static TI RebuildInput<T, TI, TR>(this TI input) where T: class, new() where TR : IBaseAdvanceService<T> where TI : class, new() { return input.BuildEntity<T, TI, TR>().BuildInput<TI, T>(); } in the controller: public ActionResult Create() { return View(new Organisation().BuildInput<OrganisationInput, Organisation>()); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(OrganisationInput o) { if (!ModelState.IsValid) { return View(o.RebuildInput<Organisation,OrganisationInput, IOrganisationService>()); } organisationService.SaveOrUpdate(o.BuildEntity<Organisation, OrganisationInput, IOrganisationService>()); return RedirectToAction("Index"); } The real Map method public static object Map(object a, object b) { var lookups = GetLookups(); var propertyInfos = a.GetType().GetProperties(); foreach (var pa in propertyInfos) { var value = pa.GetValue(a, null); // property with the same name in b var pb = b.GetType().GetProperty(pa.Name); if (pb == null) { continue; } if (pa.PropertyType == pb.PropertyType) { pb.SetValue(b, value, null); } else if (lookups.Contains(pa.Name) && pa.PropertyType == typeof(LookupItem)) { pb.SetValue(b, (pa.GetValue(a, null) as LookupItem).GetSelectList(pa.Name), null); } else if (lookups.Contains(pa.Name) && pa.PropertyType == typeof(object)) { pb.SetValue(b, pa.GetValue(a, null).ReadSelectItemValue(), null); } else if (pa.PropertyType == typeof(long) && pb.PropertyType == typeof(Organisation)) { pb.SetValue(b, pa.GetValue<long>(a).ReadOrganisationId(), null); } else if (pa.PropertyType == typeof(Organisation) && pb.PropertyType == typeof(long)) { pb.SetValue(b, pa.GetValue<Organisation>(a).Id, null); } } return b; }

    Read the article

  • Automapper: Map an Enum to its [Description] attribute

    - by Seth Petry-Johnson
    I have a source object that looks like this: private class SourceObject { public Enum1 EnumProp1 { get; set; } public Enum2 EnumProp2 { get; set; } } The enums are decorated with a custom [Description] attribute that provides a string representation, and I have an extension method .GetDescription() that returns it. How do I map these enum properties using that extension? I'm trying to map to an object like this: private class DestinationObject { public string Enum1Description { get; set; } public string Enum2Description { get; set; } } I think a custom formatter is my best bet, but I can't figure out how to add the formatter and specify which field to map from at the same time.

    Read the article

  • AutoMapper Problem - List won't Map

    - by Randy Minder
    I have the following class: public class Account { public int AccountID { get; set; } public Enterprise Enterprise { get; set; } public List<User> UserList { get; set; } } And I have the following method fragment: Entities.Account accountDto = new Entities.Account(); DAL.Entities.Account account; Mapper.CreateMap<DAL.Entities.Account, Entities.Account>(); Mapper.CreateMap<DAL.Entities.User, Entities.User>(); account = DAL.Account.GetByPrimaryKey(this.Database, primaryKey, withChildren); Mapper.Map(account,accountDto); return accountDto; When the method is called, the Account class gets mapped correctly but the list of users in the Account class does not (it is NULL). There are four User entities in the List that should get mapped. Could someone tell me what might be wrong?

    Read the article

  • Automapper Type Converter from String to IEnumerable<String> is not being called

    - by Anton
    Here is my custom Type Converter. public class StringListTypeConverter : TypeConverter<String, IEnumerable<String>> { protected override IEnumerable<string> ConvertCore(String source) { if (source == null) yield break; foreach (var item in source.Split(',')) yield return item.Trim(); } } public class Source { public String Some {get;set;} } public class Dest { public IEnumerable<String> Some {get;set;} } // ... configuration Mapper.CreateMap<String, IEnumerable<String>>().ConvertUsing<StringListTypeConverter>(); Mapper.CreateMap<Source, Dest>(); The problem: StringListTypeConverter is not being called at all. Dest.Some == null.

    Read the article

  • Automapper: Ignore on condition of

    - by Kieranmaine
    Is it possible to ignore mapping a member depending on the value of a source property? For example if we have: public class Car { public int Id { get; set; } public string Code { get; set; } } public class CarViewModel { public int Id { get; set; } public string Code { get; set; } } I'm looking for something like Mapper.CreateMap<CarViewModel, Car>() .ForMember(dest => dest.Code, opt => opt.Ignore().If(source => source.Id == 0)) So far the only solution I have is too use two different view model and create different mappings for each one.

    Read the article

  • AutoMapper: setup member name matching convention

    - by epitka
    I tried setting up a member name mapping convention so that the source members ending with a "Id" are mapped to destination members without Id. For example UserId - User How does one do this? I tried using SourceMemberNameTransformer without success. Also tried using RecognizePostfixes(). this.SourceMemberNameTransformer = s => { return s.Replace("Id", string.Empty); };

    Read the article

  • AutoMapper a viable alternative to two way databinding using a FormView?

    - by tbone
    I've started using the FormView control to enable two way databinding in asp.net webforms. I liked that it saved me the trouble of writing loadForm and unloadForm routines on every page. So it seemed to work nicely at the start when I was just using textboxes everywhere....but when it came time to start converting some to DropDownLists, all hell broke lose. For example, see: http://stackoverflow.com/questions/2435185/not-possible-to-load-dropdownlist-on-formview-from-code-behind ....and I had many additional problems after that. So I happened upon an article on AutoMapper, which I know very little about yet, but from the sounds of it, this might be a viable alternative to two-way databinding a form to an domain entity object? From what I understand, AutoMapper basically operates on naming convention, so, it will look for matched names properties(?) on the source and destination objects. So, basically, I have all my domain entities (ie: Person) with properties (FirstName, LastName, Address, etc)....what I would like to be able to do is declare my asp controls with those exact same names, and have automapper do the loading and unloading. One obvious caveat is that AutoMapper would have to know the proper property name for each control type, ie: Person.FirstName -- form.FirstName*.Text* Person.Country -- form.Country.SelectedValue Person.IsVerified -- form.IsVerified.Checked ....so it would have to have the smarts to find the control on the form, determine its type, and then load/unload between the domain object and the webform control into the proper property of the control. So if this worked, a person could just get rid of the cursed FormView control entirely, and it would be just one line of code each for binding and unbinding a webform. Possible?

    Read the article

  • Can Automapper populate a strongly typed object from the data in a NameValueCollection?

    - by Seth Petry-Johnson
    Can Automapper map values from a NameValueCollection onto an object, where target.Foo receives the value stored in the collection under the "Foo" key? I have a business object that stores some data in named properties and other data in a property bag. Different views make different assumptions about the data in the property bag, which I capture in page-specific view models. I want to use AutoMapper to map both the "inherent" attributes (the ones that always exist) as well as the "dynamic" attributes (the ones that vary per view and may or may not exist).

    Read the article

  • Can Fluent nhibernate's automapper be configured to handle private readonly backing fields?

    - by Mark Rogers
    I like private readonly backing fields because some objects are mostly read-only after creation, and for collections, which rarely need to be set wholesale (instead using collection methods to modify the collection). For example: public class BuildingType : DomainEntity { /* rest of class */ public IEnumerable<ActionType> ActionsGranted { get { return _actionsGranted; } } private readonly IList<ActionType> _actionsGranted = new List<ActionType>(); private readonly Image _buildingTile; public virtual Image BuildingTile { get { return _buildingTile; } } } But as far as I remember fluent-nhibernate's automapper never had a solution for private readonly backing fields, I'm wondering if that's changed in the last few months. So here's my question: How do I configure automapper or create an automapping convention to map private readonly backing fields?

    Read the article

  • How to configure AutoMapper if not ASP.net Application?

    - by alex
    I'm using AutoMapper in a number of projects within my solution. These projects may be deployed independantly, across multiple servers. In the documentation for AutoMapper it says: If you're using the static Mapper method, configuration only needs to happen once per AppDomain. That means the best place to put the configuration code is in application startup, such as the Global.asax file for ASP.NET applications. Whilst some of the projects will be ASP.net - most of these are class libraries / windows services. Where should I be configuring my mappings in this case?

    Read the article

  • Can I configure AutoMapper to read from custom column names when mapping from IDataReader?

    - by rohancragg
    Psuedo code for mapping configuration (as below) is not possible since the lambda only lets us access Type IDataReader, wheras when actually mapping, AutoMapper will reach into each "cell" of each IDataRecord while IDataReader.Read() == true: var mappingConfig = Mapper.CreateMap<IDataReader, IEnumerable<MyDTO>>(); mappingConfig.ForMember( destination => destination.???, options => options.MapFrom(source => source.???)); Can anyone think of a way to do this using AutoMapper configuration at runtime or just some other dynamic approach that meets the requirement below. The requirement is to support any incoming IDataReader which may have column names that don't match the property names of MyDTO and there is no naming convention I can rely on. Instead we'll ask the user at runtime to cross-reference the expected column names with the actual column names found in the IDataReader via IDataReader.GetSchemaTable().

    Read the article

  • How to map an array to multiple properties using AutoMapper?

    - by Dror Helper
    I need to map a single fixed sized array array to multiple properties. For example given this class: public class Source { public int[] ItemArray{get;set} // always 4 items } I want to map the array to this class public class Dest { public int Item1{get;set;} public int Item1{get;set;} public int Item1{get;set;} public int Item1{get;set;} } Is there a simple way to do it with AutoMapper (without actually mapping each individual field)?

    Read the article

  • Is it possible to use AutoMapper to wrap methods?

    - by Woj
    I have two classes: public class TestClass1 { public int TestInt { get; set; } public void TestMethod() { // Do something } } public class TestClass2 { public int TestInt { get; set; } public void TestMethod() { // Do something } } I want to create interface that I can use for both classes. The easiest solution is to implement the interface on TestClass1 and TestClass2 but I don;t have access to the implementation of these classes (external dll). I was wondering if I can create new interface and use AutoMapper to map TestClass1 and TestClass2 to ITestInterface: public interface ITestInterface { int TestInt { get; set; } void TestMethod(); }

    Read the article

  • Is it possible to use AutoMapper to map methods?

    - by Woj
    I have two classes: public class TestClass1 { public int TestInt { get; set; } public void TestMethod() { // Do something } } public class TestClass2 { public int TestInt { get; set; } public void TestMethod() { // Do something } } I want to create interface that I can use for both classes. The easiest solution is to implement the interface on TestClass1 and TestClass2 but I don;t have access to the implementation of these classes (external dll). I was wondering if I can create new interface and use AutoMapper to map TestClass1 and TestClass2 to ITestInterface: public interface ITestInterface { int TestInt { get; set; } void TestMethod(); }

    Read the article

  • Can AutoMapper call a method on destination for each member of collection on source?

    - by YonahW
    I have two classes as below. public class Destination { public Destination() { _StringCollection = new List<String>(); } private ICollection<String> _StringCollection; public IEnumerable<String> StringCollection { get { return _StringCollection.AsEnumerable<String>(); } } public void AddString(string str) { _StringCollection.Add(str); } } public class Source { public List<String> StringCollection { get; set; } } I would like to map that for each member of source call AddString(member) on Destination. I thought that maybe I could do something with a custom resolver but can't seem to figure out how.

    Read the article

  • Can AutoMapper create a map for an interface and then map with a derived type?

    - by TheCloudlessSky
    I have an interface IFoo: public interface IFoo { int Id { get; set; } } And then a concrete implementation: public class Bar : IFoo { public int Id { get; set; } public string A { get; set; } } public class Baz : IFoo { public int Id { get; set; } public string B { get; set; } } I'd like to be able to map all IFoo but specifying their derived type instead: Mapper.CreateMap<int, IFoo>().AfterMap((id, foo) => foo.Id = id); And then map (without explicitly creating maps for Bar and Baz): var bar = Mapper.Map<int, Bar>(123); // bar.Id == 123 var baz = Mapper.Map<int, Baz>(456); // baz.Id == 456 But this doesn't work in 1.1. I know I could specify all Bar and Baz but if there are 20 of these, I'd like to not have to manage them and rather just have what I did above for creating the map. Is this possible?

    Read the article

  • Entity Framework + AutoMapper ( Entity to DTO and DTO to Entity )

    - by vbobruisk
    Hello. i got some problems using EF with AutoMapper. =/ for example : i got 2 related entities ( Customers and Orders ) and theyr DTO classes : class CustomerDTO { public string CustomerID {get;set;} public string CustomerName {get;set;} public IList< OrderDTO Orders {get;set;} } class OrderDTO { public string OrderID {get;set;} public string OrderDetails {get;set;} public CustomerDTO Customers {get;set;} } //when mapping Entity to DTO the code works Customers cust = getCustomer(id); Mapper.CreateMap< Customers, CustomerDTO (); Mapper.CreateMap< Orders, OrderDTO (); CustomerDTO custDTO = Mapper.Map(cust); //but when i try to map back from DTO to Entity it fails with AutoMapperMappingException. Mapper.Reset(); Mapper.CreateMap< CustomerDTO , Customers (); Mapper.CreateMap< OrderDTO , Orders (); Customers customerModel = Mapper.Map< CustomerDTO ,Customers (custDTO); // exception is thrown here Am i doeing something wrong ? Thanks in Advance !

    Read the article

  • In which order is model binding and validation done in ASP.NET MVC 2?

    - by Simon Bartlett
    I am using ASP.NET MVC 2, and am using a view-model per view approach. I am also using Automapper to map properties from my domain-model to the view-model. Take this example view-model (with Required data annotation attributes for validation purposes): public class BlogPost_ViewModel { public int Id { get; set; } [Required] public string Title { get; set; } [Required] public string Text { get; set; } } In the post editor view I am using a rich text editor (CKeditor). Because CKeditor is a HTML editor, I ideally need CKeditor to HTMLencode the user's input when the form is submitted, so that ASP.NET's input validation does not complain. This is not a problem as CKeditor has this functionality built in, however I need CKeditor's output decoded before mapping back to the domain object (via Automapper). I am wanting to add a new property (to the view-model above) to solve this, as follows: public string HTMLEncodedText { get { return HTMLEncode(Text); } set { Text = HTMLDecode(value); } } I can then bind this property to CKeditor in the view, but still use Automapper to map the 'Text' property in the controller - all without having to turn input-validation off. My question is: do you know how the model binding and validation process in ASP.NET MVC 2 works? Are all model properties binded before validation is carried out? Or is each individual property get validated when it is being set. I think ideally for my idea to work, all properties need to be set before the model is validated.

    Read the article

< Previous Page | 1 2 3 4  | Next Page >