Giter Site home page Giter Site logo

cezarypiatek / mappinggenerator Goto Github PK

View Code? Open in Web Editor NEW
1.0K 31.0 121.0 1.84 MB

:arrows_counterclockwise: "AutoMapper" like, Roslyn based, code fix provider that allows to generate mapping code in design time.

Home Page: https://marketplace.visualstudio.com/items?itemName=54748ff9-45fc-43c2-8ec5-cf7912bc3b84.mappinggenerator

License: MIT License

C# 98.69% PowerShell 1.31%
roslyn code-generation mapping automapper codegenerator mapper dotnet c-sharp vsix visual-studio

mappinggenerator's Introduction

WHY THIS PROJECT IS ARCHIVED - EXPLANATION


MappingGenerator is discontinued in the form of FOSS. I spent the last three months (March 2021 - June 2021) working hard on improving MappingGenerator. I solved many issues and added a bunch of new cool features. I also made a general refactoring which restored the project maintainability. All of that cost me a lot of my private time and I did it all by myself, so I decided to convert MappingGenerator into a commercial product. A perpetual license for a new version of MappingGenerator can be obtained via the official product website https://www.mappinggenerator.net/

I would like to thank all of you who contributed to this product by reporting issues, testing, authoring PRs, or buying me coffee. PR authors (except the Only README Updaters) and Coffee Buyers will be awarded with a special license for MappingGenerator for free - I will send them an email with details in a few days.

๐Ÿ”ฅ Important Links:


Mapping Generator Tweet

"AutoMapper" like, Roslyn based, code fix provider that allows to generate mapping code in design time. Read more Mapping Generator โ€“ Design Time Alternative to AutoMapper

You can download it as Visual Studio Extension from Visual Studio Marketplace.

Motivation

The reasons behind why I don't use AutoMapper

Contributing

Before you start any contributing work, please read the contribution guideline

Supported IDE

VisualStudio.

Install as VSIX from Market place or as a NuGet package. Verify your Roslyn integration option in case you are using R#.

JetBrains Rider

Install as a NuGet package

VSCode

Install as a NuGet package or use this instruction to install from VSIX

Using along with Resharper

If you are not able to open Roslyn refactoring menu (ctr + .) please verify your Resharper settings related to Visual Studio Integration or Visual Studio code analysis (depends on the R# version). For more information please check #50

resharper settings

Main features

Generate mapping method body

Pure mapping method

Non-void method that takes single parameter

public UserDTO Map(UserEntity entity)
{
    
}

Generating pure mapping method implementation

Updating method

Void method that takes two parameters

public void Update(UserDTO source, UserEntity target)
{
    
}

Generating update method implementation

Mapping Constructor

Constructor method that takes single complex parameter

public UserDTO(UserEntity user)
{
    
}

Generating mapping constructor implementation

Constructor method that takes more than one parameter

public UserDTO(string firstName, string lastName, int age, int cash)
{
}

Generating multi-parameter constructor

Updating member method

Void member method that takes single parameter

public void UpdateWith(UserEntity en)
{
    
}

Generating update member method imeplementation

Void member method with more than one parameter

public void Update(string firstName, string lastName, int age)
{
}

Generate inline code for fixing Compiler Errors:

CS0029 Cannot implicitly convert type 'type' to 'type'

cs0029

CS0266 Cannot implicitly convert type 'type1' to 'type2'. An explicit conversion exists (are you missing a cast?)

cs0266

CS7036 There is no argument given that corresponds to the required formal parameter

CS7036

Other mappings

  • Complete empty initialization block Generate initialization bloc

  • Complete empty initialization block in lambda expression Expression<Func<T,T2>> = (T) => new T2{} initialization block in lambda expression

  • Provide local accessible variables as parameters for method and constructor invocation locals as parameters

  • Create missing mapping lambda
    mapping lambda

  • Generate ICloneable interface implementation generate clone method

Object scaffolding

sample scaffolding

Mapping rules

  • Mapping Property-To-Property

    target.FirstName = source.FirstName;
    target.LastName = source.LastName;
  • Mapping Method Call-To-Property

    target.Total = source.GetTotal()
  • Flattening with sub-property

    target.UnitId = source.Unit.Id
  • Mapping complex property

     target.MainAddress = new AddressDTO(){
    	BuildingNo = source.MainAddress.BuildingNo,
    	City = source.MainAddress.City,
    	FlatNo = source.MainAddress.FlatNo,
    	Street = source.MainAddress.Street,
    	ZipCode = source.MainAddress.ZipCode
    };
  • Mapping collections

    target.Addresses = source.Addresses.Select(sourceAddresse => new AddressDTO(){
      BuildingNo = sourceAddresse.BuildingNo,
      City = sourceAddresse.City,
      FlatNo = sourceAddresse.FlatNo,
      Street = sourceAddresse.Street,
      ZipCode = sourceAddresse.ZipCode
    }).ToList().AsReadOnly();
  • Unwrapping wrappers

    customerEntity.Kind = cutomerDTO.Kind.Selected;
      public enum CustomerKind
      {
          Regular,
          Premium
      }
    
      public class Dropdown<T>
      {
          public List<T> AllOptions { get; set; }
    
          public T Selected { get; set; }
      }
    
      public class CustomerDTO
      {
          public string Name { get; set; }
          public Dropdown<CustomerKind> Kind { get; set; }
      }
    
      public class UserEntity
      {
          public string Name { get; set; }
          public CustomerKind Kind { get; set; }
      }
  • Using existing direct mapping constructor

    target.MainAddress = new AddressDTO(source.MainAddress);
  • using existing multi-parameter constuctor

    this.User =  new UserDTO(firstName: entity.FirstName, lastName: entity.LastName, age: entity.Age);

mappinggenerator's People

Contributors

cezarypiatek avatar gbarrs-at-em avatar jzabroski avatar kidchenko avatar wachulski avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mappinggenerator's Issues

Generate mapping from generics

My converters are generics and your generator generate empty methods with these converters.

code

Do you think you can do something about my scenario?

Generate as extension methods?

Looks like a great tool. I think a good enhancement would be to generate the mapping code as an extension method.

userEntity.ToUserDTO()

Enhancement to generate mapping that creates new or updates existing

I think it'd be useful to allow an additional parameter that is the same as the destination type which could be used to update an existing object if it exists. So, given a signature like this:

public MyEntity Map(MyModel model, MyEntity entity)
{
}

It could generate code like this:

public MyEntity Map(MyModel model, MyEntity entity)
{
    entity = entity ?? new MyEntity();
    entity.Prop1 = model.Prop1;
    entity.Prop2 = model.Prop2;
    return entity;
}

It should work the same if using an optional parameter:
public MyEntity Map(MyModel model, MyEntity entity = null)

What do you think?

Loosing properties

When using the MappginGenerator, I lose my properties UnitId/InventoryUnitId and Category/UnitCategory:

image

Is it possible to detect slight variation in property name or at least not overriding the entire method and keeping my unmatched properties?

Creating object in factory method

Hello Cezary,

I tried to use your extension and found out that it lacks one functionality that I wanted to use.

From DTO / command class I want to create an entity. For example from CreateProductCommand I run ToProduct method.:

    public class CreateProductCommand
    {

        public string Name { get; set; }

        public decimal Price { get; set; }

        public Category Category { get; set; }

        public Tag[] Tags { get; set; }

        public Product ToProduct()
        {
            return new Product(); //<----
        }
    }

    public class Product
    {
        public Product(string name, decimal price, Category category, Tag[] tags)
        {
            Id = new Guid();
            Name = name;
            Price = price;
            Category = category;
            Tags = tags;
        }

        public Guid Id { get; private set; }

        public string Name { get; private set; }

        public decimal Price { get; private set; }

        public Category Category { get; private set; }

        public Tag[] Tags { get; private set; }
    }

Would be able to provide auto-generating data to this constructor? Or maybe where should I find such option in the extension to try to add it on my own.

when class only one prop not working

sample code

public class Person
        {
            public int Age { get; set; }
            public string Name { get; set; }

            public Person(int age)
            {
            }
        }

but

 public Person(int age,string name)
            {
            }

it's working

env:
vs 2019 preview 3
win10 1903

Support for Visual Studio 2019 beta

Hi,

First of all congratulate on this amazing plugin!

I just tried to install in visual studio 2019 it said there's a pre-requisite and can't be installed.

Do you know what else do I need to install before installing this plugin?

Thanks,

Generate mapping code for Expression<Func<fromType, toType>>

Hello,

Thanks for the great project. We even once had tweeting about the particular subject before and agreed need of kind of project.

This is a common pattern in my coding which allows me to use the projection in Entity Framework queries.

I think it is a good idea to support that particular use case.

public fromType{
        ....
        public static Expression<Func<fromType, toType>> Projection = (ft) => 
             new toType{
                .....
            };
}

Question: Complex expression mapping

Consider the following models:

namespace ModelMapping.Application
{
    public class Person
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
    }
}

namespace ModelMapping.Domain
{
    public class Person
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
    }
}

how can I map the following expression?

static Expression<Func<IQueryable<Domain.Person>, IOrderedQueryable<Domain.Person>>> MyFunction(Expression<Func<IQueryable<Application.Person>, IOrderedQueryable<Application.Person>>> expression) { }

I use this expression like this:

Expression<Func<IQueryable<Application.Person>, IOrderedQueryable<Application.Person>>> expression = persons => persons.OrderBy(p => p.Name);

Thank you.

Improve naming for lambda parameter in collection mapping

  1. Convert plural to singular form
 public static List<YY> Map(List<XX> categories)
        {
            return categories.Select(category => new YY()
            {
                Id = category.Id,
                Name = category.Name
            }).ToList();
        }
  1. Use lambda parameter name as a prefix
 public static List<ZZ> Map(List<XX> categories)
        {
            return categories.Select(category => new ZZ()
            {
                CategoryId = category.Id,
                CategoryName = category.Name
            }).ToList();
        }
  1. Use item for lambda parameter name for generic collection name
public static List<ZZ> MapNew(List<XX> dictionary)
        {
            return dictionary.Select(item => new ZZ()
            {
                Id = item.Id,
                Name = item.Name
            }).ToList();
        }
  1. Convert plural to singular from name postfixed with generic collection name
public static List<ZZ> MapNew(List<XX> usersList)
        {
            return usersList.Select(user => new ZZ()
            {
                Id = user.Id,
                Name = user.Name
            }).ToList();
        }

Mapping Nullable<bool> to NotNullable<bool>

Hello.
i tried your extension (Version 1.12.306) at some code. Its great but i think i have found a small issue.

I have a domain object with a nullable bool property and it should be mapped to not nullable bool dto.
This is bad design.. i know that :)

The MappingGenerator generates:

private Dto ToDomain(DomainObject domainobject)
{
   return new Dto(notnullableproperty: domainobject.nullableproperty.Value);
}

This code will fail when the nullableproperty is null.
I suggest to use nullableproperty.GetValueOrDefault() instead

[Enhancement] Synchronization means through attribute like [SyncedMapping] etc.

Right now we have perfect means to create mappings. I'd would be useful too to resync the changes as entities/DTOs evolve over time (cliche, I know).

What about marking types/methods with attributes from e.g. MappingGenerator.Annotations (a dedicated NuGet) [SyncedMapping] to indicate the engine to look for changes and update mappings on the fly? It'd be particularly useful in scenarios when some entity-DTO pairs appear in multiple mappings as aggregate children.

I expect that one'd want some exclusion rules then too, e.g. custom mapping method discovery for not to loose custom changes:

dto.Accounts = MapAccountsInCustomWay(entity)
// ...

void MapAccountsInCustomWay(MyEntity entity)

It can be developed incrementally: 1) diagnostics only (i.e warnings) 2) code fixes (auto-sync updates on the fly).

Possible Code-Generation for TDest Map(TSource source, TDest dest)

Because Automapper has a similar interface method, it would be nice to generate a mapping with the following method-signature:
TDest Map(TSource source, TDest dest)

At the moment this code suggests a mapping but it looks like this:

public override MyDest Map(MySource source, MyDest target)
  {
    return new MyDest();
  }

Would it be possible to suggest a mapping generation similar to the mapping if the method wouldn't return something ? Maybe an additional suggestion or a fallback if the mapping is just the default-constructor.

p.s. thanks for this project :)

Inherited properties not generating

I have an entity that inherits Microsoft.AspNet.Identity.EntityFramework.IdentityUser from packages\Microsoft.AspNet.Identity.EntityFramework.2.2.1\lib\net45\Microsoft.AspNet.Identity.EntityFramework.dll. The properties in my entity get mapped, but not the ones from IdentityUser such as "Email". Here's what the method starts out as:

public static ApplicationUserEntity ToEntity(this UserModel model)
{
}

Base class properties not mapped

I have a class ChildModel inheriting from ModelBase which contains an Id property and a class Child inheriting from Entity which also contains an Id property of the same type. When I try to generate a mapping from Child to ChildModel all properties are mapped except the Id property.

It is not difficult to add it manually in my case but if there were more properties it would become a bit annoying. I don't know if this is intended behavior or just something you haven't thought about.

UPDATE: I just noticed something else. Curiously enough, when I generate code for the opposite mapping i.e ChildModel to Child, I do get mapping code for the Id property.

analyze code for added properties

Support that you have generated code. Then you add another properties. And you want those generated too. And remember where you should add

Exception in VS2017 Community

As soon as the 'Generating mapping code" context menu gains focus:

System.NullReferenceException : Object reference not set to an instance of an object. at MappingGenerator.MappingGenerator.<MapTypes>d__4.MoveNext() at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext() at Microsoft.CodeAnalysis.SyntaxList1.CreateNode(IEnumerable1 nodes) at Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpSyntaxGenerator.AsStatementList(IEnumerable1 nodes) at Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpSyntaxGenerator.CreateBlock(IEnumerable1 statements) at Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpSyntaxGenerator.MethodDeclaration(String name,IEnumerable1 parameters,IEnumerable1 typeParameters,SyntaxNode returnType,Accessibility accessibility,DeclarationModifiers modifiers,IEnumerable1 statements) at Microsoft.CodeAnalysis.Editing.SyntaxGenerator.MethodDeclaration(IMethodSymbol method,String name,IEnumerable1 statements) at async MappingGenerator.MappingGeneratorCodeFixProvider.GenerateMappingMethodBody(<Unknown Parameters>) at async Microsoft.CodeAnalysis.CodeActions.CodeAction.GetChangedSolutionAsync(<Unknown Parameters>) at async Microsoft.CodeAnalysis.CodeActions.CodeAction.ComputeOperationsAsync(<Unknown Parameters>) at async Microsoft.CodeAnalysis.CodeActions.CodeAction.ComputePreviewOperationsAsync(<Unknown Parameters>) at async Microsoft.CodeAnalysis.CodeActions.CodeAction.GetPreviewOperationsAsync(<Unknown Parameters>) at async Microsoft.CodeAnalysis.Editor.Implementation.Suggestions.SuggestedAction.GetPreviewResultAsync(<Unknown Parameters>) at async Microsoft.CodeAnalysis.Editor.Implementation.Suggestions.SuggestedActionWithNestedFlavors.<>c__DisplayClass11_0.<GetPreviewAsync>b__0(<Unknown Parameters>) at async Microsoft.CodeAnalysis.Extensions.IExtensionManagerExtensions.PerformFunctionAsync[T](<Unknown Parameters>)

Just not working in my VS2017 Pro/Community

Hi Cezary,

I've used your plug-in successfully in a previous contract but though I've installed it, it just doesn't present itself. It shows as installed within the VS Extensions & Updates but that's as much as I get. Any hints to try to resolve it?

I'm running VS2017 Vsn 15.9.7 and get the same issue on the latest Community Edition

Cheers,

Will

Error when opening quick actions menu

I've just installed this extension, but get an error when opening the Visual Studio "Quick Actions" menu, before I've even hit "Generate mapping code". Stack trace:

System.NullReferenceException : Object reference not set to an instance of an object.
   at Microsoft.CodeAnalysis.CSharp.Syntax.SyntaxReplacer.Replacer`1.<>c.<.ctor>b__10_0(SyntaxNode n)
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Linq.Enumerable.<ConcatIterator>d__59`1.MoveNext()
   at System.Collections.Generic.HashSet`1.UnionWith(IEnumerable`1 other)
   at System.Collections.Generic.HashSet`1..ctor(IEnumerable`1 collection,IEqualityComparer`1 comparer)
   at System.Collections.Generic.HashSet`1..ctor(IEnumerable`1 collection)
   at Microsoft.CodeAnalysis.CSharp.Syntax.SyntaxReplacer.Replacer`1..ctor(IEnumerable`1 nodes,Func`3 computeReplacementNode,IEnumerable`1 tokens,Func`3 computeReplacementToken,IEnumerable`1 trivia,Func`3 computeReplacementTrivia)
   at Microsoft.CodeAnalysis.CSharp.Syntax.SyntaxReplacer.Replace[TNode](SyntaxNode root,IEnumerable`1 nodes,Func`3 computeReplacementNode,IEnumerable`1 tokens,Func`3 computeReplacementToken,IEnumerable`1 trivia,Func`3 computeReplacementTrivia)
   at Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode.ReplaceCore[TNode](IEnumerable`1 nodes,Func`3 computeReplacementNode,IEnumerable`1 tokens,Func`3 computeReplacementToken,IEnumerable`1 trivia,Func`3 computeReplacementTrivia)
   at Microsoft.CodeAnalysis.SyntaxNodeExtensions.ReplaceNode[TRoot](TRoot root,SyntaxNode oldNode,SyntaxNode newNode)
   at async MappingGenerator.SyntaxGeneratorExtensions.ReplaceNodes(<Unknown Parameters>)
   at async MappingGenerator.MappingGeneratorRefactoring.GenerateMappingMethodBody(<Unknown Parameters>)
   at async Microsoft.CodeAnalysis.CodeActions.CodeAction.GetChangedSolutionAsync(<Unknown Parameters>)
   at async Microsoft.CodeAnalysis.CodeActions.CodeAction.ComputeOperationsAsync(<Unknown Parameters>)
   at async Microsoft.CodeAnalysis.CodeActions.CodeAction.GetPreviewOperationsAsync(<Unknown Parameters>)
   at async Microsoft.CodeAnalysis.Editor.Implementation.Suggestions.SuggestedAction.GetPreviewResultAsync(<Unknown Parameters>)
   at async Microsoft.CodeAnalysis.Editor.Implementation.Suggestions.SuggestedActionWithNestedFlavors.<>c__DisplayClass11_0.<GetPreviewAsync>b__0(<Unknown Parameters>)
   at async Microsoft.CodeAnalysis.Extensions.IExtensionManagerExtensions.PerformFunctionAsync[T](<Unknown Parameters>)

I'm on Visual Studio 2017, version 15.9.4.

Before opening the Quick Actions menu, I've typed this stub:

public static class Mapper
{
    public static MyDTO Map(MyEntity entity)
}

Installed VS Extension... and now what?

Hi,

I am trying to understand how to use your extension. I installed the vsix in my VS 2017 community and I can see it in my Extensions and Updates (v. 1.3.125). And now? What do I have to do to use it? I cannot see any "Generate Mapping ..." when I hover the yellow light bulbs on the left side of my code window. What am I missing?

Best,
Alex

Support for Expression<Func<in T, out TResult>>

Hey! Awesome project. I too thought automapper got in the way in a large project.

I'd like to request a further feature. I'm working a lot with IQueryable projections and within those c# methods aren't really supported as far as I know?

So I make a few mapping expressions like this:

 public static Expression<Func<Core.Models.Entities.Member, QueryResult.Member>> Map = member => new Member
{
                FirstName = member.FirstName
};

which I then use like this:

var items = members
                .Select(QueryResult.Member.Map)
                .ToList();

I cannot find support for this feature atm and would really like to see it implemented :)

Question: applying new fields to the mapping?

Hi,
I've read your blog post for why use compile-time mappings instead of AutoMapper and I agree with your claims against it mostly, however there's one thing important for me to use AutoMapper for I wonder if this Roslyn mapper solves. Let's say we have types UserDTO and UserEntity, and we generated a mapping. Now someone adds field "Locale" to both UserEntity and UserDTO and forgets the mapping(s) exist to add the field there; I've seen all the time, which AutoMapper solves. Will this generator emit some diagnostic about missed mapping opportunity?

Support for Visual Studio Community 2015

Hi, I have a question. Can MappingGenerator be installed on Visual Studio Community 2015?
I got the following installation error:

1-3-2018 11:22:45 - Microsoft VSIX Installer
1-3-2018 11:22:45 - -------------------------------------------
1-3-2018 11:22:45 - Initializing Install...
1-3-2018 11:22:45 - Extension Details...
1-3-2018 11:22:45 - Identifier : MappingGenerator.de964118-68da-48b7-9b74-0bf8a2c5bfa3
1-3-2018 11:22:45 - Name : MappingGenerator
1-3-2018 11:22:45 - Author : cepi
1-3-2018 11:22:45 - Version : 1.0
1-3-2018 11:22:45 - Description : Roslyn based code fix provider that allows to generate mapping code in design time.
1-3-2018 11:22:45 - Locale : en-US
1-3-2018 11:22:45 - MoreInfoURL :
1-3-2018 11:22:45 - InstalledByMSI : False
1-3-2018 11:22:45 - SupportedFrameworkVersionRange : [4.5,)
1-3-2018 11:22:45 -
1-3-2018 11:22:45 - SignatureState : Unsigned
1-3-2018 11:22:45 - Supported Products :
1-3-2018 11:22:45 - Microsoft.VisualStudio.Community
1-3-2018 11:22:45 - Version : [15.0,)
1-3-2018 11:22:45 -
1-3-2018 11:22:45 - References :
1-3-2018 11:22:45 - Signature Details...
1-3-2018 11:22:45 - Extension is not signed.
1-3-2018 11:22:45 -
1-3-2018 11:22:45 - Searching for applicable products...
1-3-2018 11:22:48 - Found installed product - Microsoft Visual Studio Professional 2013
1-3-2018 11:22:48 - Found installed product - Microsoft Visual Studio 2013 Shell (Integrated)
1-3-2018 11:22:48 - Found installed product - Microsoft Visual Studio Community 2015
1-3-2018 11:22:48 - Found installed product - Microsoft Visual Studio 2015 Shell (Integrated)
1-3-2018 11:22:48 - Found installed product - Global Location
1-3-2018 11:22:48 - Found installed product - ssms
1-3-2018 11:22:48 - VSIXInstaller.NoApplicableSKUsException: This extension is not installable on any currently installed products.
at VSIXInstaller.App.InitializeInstall(Boolean isRepairSupported)
at VSIXInstaller.App.InitializeInstall()
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.Execute()

[Feature Request] - Enum <-> String

In the case of attributes with the same name and one is enum while the other one is string, use the enum tryparse and enum description function to do 2 way transform.

Exception when generating mapping

I create this code:

public Thing1 Test(Thing2 thing)
{
}

Where Thing1 and Thing2 have some properties in common, and other, non-common properties. Oh and they might also have properties matching by name but not by type. And maybe Thing1 has only parameter-less constructors.

Gettings this exception soon as I hit the generate menu:

System.NullReferenceException : Object reference not set to an instance of an object.
   at MappingGenerator.MappingEngine.<>c__DisplayClass9_2.<TryToCreateMappingExpression>b__3(MappingElement x)
   at System.Linq.Enumerable.Any[TSource](IEnumerable`1 source,Func`2 predicate)
   at MappingGenerator.MappingEngine.<>c__DisplayClass9_1.<TryToCreateMappingExpression>b__2(MappingElement foundElement)
   at MappingGenerator.IgnorableMappingSourceFinder.FindMappingSource(String targetName,ITypeSymbol targetType)
   at MappingGenerator.MappingEngine.<>c__DisplayClass11_0.<MapUsingSimpleAssignment>b__0(IPropertySymbol property)
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at MappingGenerator.MappingEngine.MapUsingSimpleAssignment(SyntaxGenerator generator,IEnumerable`1 targets,IMappingSourceFinder sourceFinder,MappingPath mappingPath,SyntaxNode globalTargetAccessor)
   at MappingGenerator.MappingEngine.AddInitializerWithMapping(ObjectCreationExpressionSyntax objectCreationExpression,IMappingSourceFinder mappingSourceFinder,ITypeSymbol createdObjectTyp,MappingPath mappingPath)
   at MappingGenerator.MappingEngine.TryToCreateMappingExpression(MappingElement source,ITypeSymbol targetType,MappingPath mappingPath)
   at MappingGenerator.MappingEngine.MapExpression(MappingElement element,ITypeSymbol targetType,MappingPath mappingPath)
   at MappingGenerator.MappingEngine.MapExpression(ExpressionSyntax sourceExpression,ITypeSymbol sourceType,ITypeSymbol destinationType)
   at MappingGenerator.MappingGeneratorRefactoring.GenerateMappingCode(IMethodSymbol methodSymbol,SyntaxGenerator generator,SemanticModel semanticModel)
   at async MappingGenerator.MappingGeneratorRefactoring.GenerateMappingMethodBody(<Unknown Parameters>)
   at async Microsoft.CodeAnalysis.CodeActions.CodeAction.GetChangedSolutionAsync(<Unknown Parameters>)
   at async Microsoft.CodeAnalysis.CodeActions.CodeAction.ComputeOperationsAsync(<Unknown Parameters>)
   at async Microsoft.CodeAnalysis.CodeActions.CodeAction.GetPreviewOperationsAsync(<Unknown Parameters>)
   at async Microsoft.CodeAnalysis.Editor.Implementation.Suggestions.SuggestedAction.GetPreviewResultAsync(<Unknown Parameters>)
   at async Microsoft.CodeAnalysis.Editor.Implementation.Suggestions.SuggestedActionWithNestedFlavors.<>c__DisplayClass11_0.<GetPreviewAsync>b__0(<Unknown Parameters>)
   at async Microsoft.CodeAnalysis.Extensions.IExtensionManagerExtensions.PerformFunctionAsync[T](<Unknown Parameters>)

Is it... that I am doing something that I should not do, or is it some kind of anomaly?

Set target null if source is null

I would find it helpful if null checking code was generated along with the mapping code. Any thoughts on this?

Example:

public void Map(MyModel model, MyEntity entity)
{
    if (model == null)    //New code to generate
    {
        entity = null;
        return;
    }                    //End new code to generate
    entity.Prop1 = model.Prop1;
    entity.Prop2 = model.Prop2;
}

or

public MyEntity Map(MyModel model, MyEntity entity)
{
    if (model == null)    //New code to generate
    {
        entity = null;
        return entity;
    }                    //End new code to generate
    entity.Prop1 = model.Prop1;
    entity.Prop2 = model.Prop2;
}

Support for F#

Any suggestions how to make this work for F#?

If that's not possible, any plans for supporting F# in the future? I'd be willing to help with implementation.

No License specified

Hi. I wanted to fork this project, but you have not specified any license.
As a suggestion MIT will be great!! :)

Can't get Mapping options in Roslyn menu

I have ReSharper installed, but disabled. Restarted VS 2017. Still no Generate Mapping Code in the Roslyn menu. I verified that the extension appears to be installed. What is required for the Generate Mapping Code to show up ?

Nullable enum to int?

I generated the following mapping :

bendingTypeDetail = new BendingTypeDetail
                    {
                      TypeNumber = args.BendingTypeDetail.TypeNumber,
                      Definition = (int) args.BendingTypeDetail.Definition,
                      Threads = new int?(value: (int) args.BendingTypeDetail.Threads.Value),
                    };

The field Definition is an enum and it has been converted right in an int. But the conversion of the field Threads, which is a nullable enum converted to nullable int, is invalid and will likely generate a null exception.

Should has been Threads = (int?) args.BendingTypeDetail.Threads

Add simplified object initialization

If code style rule "IDE0017 Object initialization can be simplified" enabled (default) in VS, generated mapping code cause the warning occurrence. Maybe it worth to consider implement simplified object initialization or added this feature as an option in the extension configuration.
map_001

Clone object mapping

It would be nice if there was a straightforward way to create a clone. I know that currently that can be accomplished by creating a mapping that takes and returns the same object, and after that alt-enter -> explicit mapping, but I was wondering if it wouldnt be better to directly generate explicit mapping in the above scenario. Writing a mapping method that takes and returns the same type doesn't really make sense in any other case, unless you want to clone (and maybe modify slightly) the passed object.

P.S: Love the tool. Saves me from writing boring code.

P.P.S: Sorry for overwhelming you with issues :D

Support For JetBrains Rider

This plugin was an indispensable part of my everyday development while developing using Visual Studio. However, now that I've switched to JetBrains Rider, I really miss the functionality that this plugin provided.

Do you have any intentions of creating a Rider plugin port for this tool?

Extension error with a null exception

Hi, thanks for the useful extension by the way.

The extension keeps crashing with a null reference exception, this started right after updating visual studio to version 15.6.4, prior versions of visual studio worked just fine with the extension.

Stack trace:
System.NullReferenceException : Object reference not set to an instance of an object.
at MappingGenerator.SymbolHelper.IsReadonlyProperty(IPropertySymbol property)
at MappingGenerator.MappingGenerator.CanBeSet(IPropertySymbol targetProperty,SyntaxNode globbalTargetAccessor,Boolean isConstructorContext)
at lMappingGenerator.MappingGenerator.d__4.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext() at Microsoft.CodeAnalysis.SyntaxList1.CreateNode(IEnumerable1 nodes) at Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpSyntaxGenerator.AsStatementList(IEnumerable1 nodes)
at Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpSyntaxGenerator.CreateBlock(IEnumerable1 statements) at Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpSyntaxGenerator.MethodDeclaration(String name,IEnumerable1 parameters,IEnumerable1 typeParameters,SyntaxNode returnType,Accessibility accessibility,DeclarationModifiers modifiers,IEnumerable1 statements)
at Microsoft.CodeAnalysis.Editing.SyntaxGenerator.MethodDeclaration(IMethodSymbol method,String name,IEnumerable`1 statements)
at async MappingGenerator.MappingGeneratorCodeFixProvider.GenerateMappingMethodBody()
at async Microsoft.CodeAnalysis.CodeActions.CodeAction.GetChangedSolutionAsync()
at async Microsoft.CodeAnalysis.CodeActions.CodeAction.ComputeOperationsAsync()
at async Microsoft.CodeAnalysis.CodeActions.CodeAction.ComputePreviewOperationsAsync()
at async Microsoft.CodeAnalysis.CodeActions.CodeAction.GetPreviewOperationsAsync()
at async Microsoft.CodeAnalysis.Editor.Implementation.Suggestions.SuggestedAction.GetPreviewResultAsync()
at async Microsoft.CodeAnalysis.Editor.Implementation.Suggestions.SuggestedActionWithNestedFlavors.PreviewChangesSuggestedAction.CreateAsync()
at async Microsoft.CodeAnalysis.Editor.Implementation.Suggestions.SuggestedActionWithNestedFlavors.GetPreviewChangesFlavor()
at async Microsoft.CodeAnalysis.Editor.Implementation.Suggestions.SuggestedActionWithNestedFlavors.CreateAllFlavors()
at async Microsoft.CodeAnalysis.Extensions.IExtensionManagerExtensions.PerformFunctionAsyncT

Disable or Include an option to disable Message "Implementation of mapping method can be generated".

At my work, we try to keep our "Messages" to 0 (which mean doing all suggested code fixes). However, on my Messages, I am getting over 200+ "Implementation of mapping method can be generated".

I know I can click on the light-bulb and do "Generate Mapping Code" on methods I actually want to run it on, therefore I prefer not to have 200+ messages telling me "Implementation of mapping method can be generated" for every available method. Because I already know it can be done.

Also, even after I generate the mapping code, the message still does not go away.

I'm requesting this message to be disabled or have an option to not show it.

T H A N K Y O U

I just wanted to send you a quick note and say thank-you for the work you have done on this project.

It has made my life ๐Ÿ’ฏ easier.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.