Skip to content

Commit

Permalink
Merge pull request #24 from AutoMapper/development
Browse files Browse the repository at this point in the history
merge to master for release
  • Loading branch information
TylerCarlson1 authored Oct 20, 2019
2 parents 0574956 + 6d8d281 commit 251df9e
Show file tree
Hide file tree
Showing 12 changed files with 60 additions and 46 deletions.
2 changes: 1 addition & 1 deletion NuGet.Config
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<packageSources>
<add key="AutoMapper" value="https://www.myget.org/F/automapperdev/api/v2" />
</packageSources>
</configuration>
50 changes: 32 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,28 +1,41 @@
<img src="https://s3.amazonaws.com/automapper/logo.png" alt="AutoMapper">

AutoMapper.Collection.EFCore
================================
`Automapper.Collection.EntityFrameworkCore` will help you mapping of EntityFramework Core DbContext-object.

Mapper.Initialize(cfg =>
{
cfg.AddCollectionMappers();
cfg.UseEntityFrameworkCoreModel<DB>(serviceProvider);
// Configuration code
});

User defined equality expressions will overwrite primary key expressions.
# AutoMapper.Collection.EntityFrameworkCore

`Automapper.Collection.EntityFrameworkCore` will help you mapping of EntityFrameowrk Core DbContext-object.

## Configuration examples

- Usage together with Dependency injection and AutoMapper.Extensions.Microsoft.DependencyInjection pacakge
```
var services = new ServiceCollection();
services
.AddEntityFrameworkInMemoryDatabase()
.AddDbContext<DB>();
services.AddAutoMapper((serviceProvider, automapper) =>
{
automapper.AddCollectionMappers();
automapper.UseEntityFrameworkCoreModel<DB>(serviceProvider);
}, typeof(DB).Assembly);
var serviceProvider = services.BuildServiceProvider();
```

**Note:** User defined equality expressions will overwrite primary key expressions.

What about comparing to a single existing Entity for updating?
--------------------------------
Automapper.Collection.EntityFramework does that as well through extension method from of DbSet<TEntity>.
Automapper.Collection.EntityFrameworkCore does that as well through extension method from of DbSet<TEntity>.

Translate equality between dto and EF object to an expression of just the EF using the dto's values as constants.

dbContext.Orders.Persist().InsertOrUpdate<OrderDTO>(newOrderDto);
dbContext.Orders.Persist().InsertOrUpdate<OrderDTO>(existingOrderDto);
dbContext.Orders.Persist().Remove<OrderDTO>(deletedOrderDto);
```
dbContext.Orders.Persist(mapper).InsertOrUpdate<OrderDTO>(newOrderDto);
dbContext.Orders.Persist(mapper).InsertOrUpdate<OrderDTO>(existingOrderDto);
dbContext.Orders.Persist(mapper).Remove<OrderDTO>(deletedOrderDto);
dbContext.SubmitChanges();
```

**Note:** This is done by converting the OrderDTO to Expression<Func<Order,bool>> and using that to find matching type in the database. You can also map objects to expressions as well.

Expand All @@ -31,6 +44,7 @@ Persist doesn't call submit changes automatically
How to get it
--------------------------------
Use NuGet Package Manager to install the package or use any of the following command in NuGet Package Manager Console.

PM> Install-Package AutoMapper.Collection.EntityFrameworkCore

```
PM> Install-Package AutoMapper.Collection.EntityFrameworkCore
```
2 changes: 1 addition & 1 deletion build.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ task compile -depends clean {
# restore all project references (creating project.assets.json for each project)
exec { dotnet restore $base_dir\AutoMapper.Collection.EFCore.sln /nologo }

exec { dotnet build $base_dir\AutoMapper.Collection.EFCore.sln -c $config $buildParam /nologo --no-restore }
exec { dotnet build $base_dir\AutoMapper.Collection.EFCore.sln -c $config $buildParam --no-restore /nologo }

exec { dotnet pack $base_dir\AutoMapper.Collection.EFCore.sln -c $config --include-symbols --no-build --no-restore --output $artifacts_dir $packageParam /nologo}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>net462</TargetFrameworks>
<TargetFrameworks>net462;netcoreapp2.0</TargetFrameworks>
<AssemblyName>AutoMapper.Collection.EntityFrameworkCore.Tests</AssemblyName>
<IsPackable>false</IsPackable>
</PropertyGroup>
Expand All @@ -19,7 +19,7 @@
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="6.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="2.1.1" />
<PackageReference Include="FluentAssertions" Version="5.4.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.9.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.1.0" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.1.1" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,11 @@ public EntityFrameworkCoreUsingMicrosoftDITests()
.AddEntityFrameworkInMemoryDatabase()
.AddDbContext<DB>(options => options.UseInMemoryDatabase("EfTestDatabase" + Guid.NewGuid()));

services.AddAutoMapper(automapper =>
services.AddAutoMapper(x =>
{
automapper.AddCollectionMappers();
automapper.UseEntityFrameworkCoreModel<DB>(services);
x.AddCollectionMappers();
x.UseEntityFrameworkCoreModel<DB>(services);
x.CreateMap<ThingDto, Thing>().ReverseMap();
}, new Assembly[0]);

this._serviceProvider = services.BuildServiceProvider();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,16 @@ namespace AutoMapper.Collection.EntityFrameworkCore.Tests
{
public class EntityFramworkCoreUsingCtorTests : EntityFramworkCoreTestsBase
{
private readonly Mapper _mapper;

public EntityFramworkCoreUsingCtorTests()
{
Mapper.Reset();
Mapper.Initialize(x =>
_mapper = new Mapper(new MapperConfiguration(x =>
{
x.AddCollectionMappers();
x.CreateMap<ThingDto, Thing>().ReverseMap();
x.UseEntityFrameworkCoreModel<DB>();
});
}));
}

protected override DBContextBase GetDbContext()
Expand All @@ -24,7 +25,7 @@ protected override DBContextBase GetDbContext()

protected override IMapper GetMapper()
{
return Mapper.Instance;
return _mapper;
}

public class DB : DBContextBase
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ namespace AutoMapper.Collection.EntityFrameworkCore.Tests
public class EntityFramworkCoreUsingDITests : EntityFramworkCoreTestsBase, IDisposable
{
private readonly ServiceProvider _serviceProvider;
private readonly Mapper _mapper;
private readonly IServiceScope _serviceScope;

public EntityFramworkCoreUsingDITests()
Expand All @@ -21,13 +22,13 @@ public EntityFramworkCoreUsingDITests()

_serviceProvider = services.BuildServiceProvider();

Mapper.Reset();
Mapper.Initialize(x =>
_mapper = new Mapper(new MapperConfiguration(x =>
{
x.ConstructServicesUsing(type => ActivatorUtilities.GetServiceOrCreateInstance(_serviceProvider, type));
x.AddCollectionMappers();
x.UseEntityFrameworkCoreModel<DB>(_serviceProvider);
});
x.CreateMap<ThingDto, Thing>().ReverseMap();
}));

_serviceScope = _serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope();
}
Expand All @@ -45,7 +46,7 @@ protected override DBContextBase GetDbContext()

protected override IMapper GetMapper()
{
return Mapper.Instance;
return _mapper;
}

public class DB : DBContextBase
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="AutoMapper.Collection" Version="5.0.0" />
<PackageReference Include="AutoMapper.Collection" Version="6.0.0-ci-*" />
</ItemGroup>

<ItemGroup>
Expand Down
4 changes: 3 additions & 1 deletion src/AutoMapper.Collection.EntityFrameworkCore/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,18 @@ namespace AutoMapper.EntityFrameworkCore
public static class Extensions
{
/// <summary>
/// Obsolete: Use Persist(IMapper) instead.
/// Create a Persistence object for the <see cref="T:System.Data.Entity.DbSet`1"/> to have data persisted or removed from
/// Uses static API's Mapper for finding TypeMap between classes
/// </summary>
/// <typeparam name="TSource">Source table type to be updated</typeparam>
/// <param name="source">DbSet to be updated</param>
/// <returns>Persistence object to Update or Remove data</returns>
[Obsolete("Use Persist(IMapper) instead.", true)]
public static IPersistence<TSource> Persist<TSource>(this DbSet<TSource> source)
where TSource : class
{
return new Persistence<TSource>(source, Mapper.Instance);
throw new NotSupportedException();
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public class GenerateEntityFrameworkCorePrimaryKeyPropertyMaps<TDatabaseContext>

public GenerateEntityFrameworkCorePrimaryKeyPropertyMaps()
{
throw new InvalidOperationException("Use UseEntityFrameworkCoreModel instead of using SetGeneratePropertyMaps.");
throw new InvalidOperationException($"Use {nameof(MapperConfigurationExpressionExtensions.UseEntityFrameworkCoreModel)} instead of using SetGeneratePropertyMaps.");
}

public GenerateEntityFrameworkCorePrimaryKeyPropertyMaps(IModel model) => _model = model;
Expand Down
13 changes: 4 additions & 9 deletions src/AutoMapper.Collection.EntityFrameworkCore/Persistence.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public class Persistence<TTo> : IPersistence<TTo>
public Persistence(DbSet<TTo> sourceSet, IMapper mapper)
{
_sourceSet = sourceSet;
_mapper = mapper;
_mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
}

public TTo InsertOrUpdate<TFrom>(TFrom from)
Expand Down Expand Up @@ -85,15 +85,12 @@ private TTo MapObject(Type type, object from, TTo to)
{
if (to == null)
{
to = (TTo)(_mapper?.Map(from, type, typeof(TTo)) ?? Mapper.Map(from, type, typeof(TTo)));
to = (TTo)_mapper.Map(from, type, typeof(TTo));
_sourceSet.Add(to);
}
else
{
if (_mapper == null)
Mapper.Map(from, to);
else
_mapper.Map(from, to);
_mapper.Map(from, to);
}
return to;
}
Expand All @@ -105,9 +102,7 @@ private Expression<Func<TTo, bool>> GetEquivalenceExpression<TFrom>(TFrom from)

private Expression<Func<TTo, bool>> GetEquivalenceExpression(Type type, object from)
{
return _mapper == null
? Mapper.Map(from, type, typeof(Expression<Func<TTo, bool>>)) as Expression<Func<TTo, bool>>
: _mapper.Map(from, type, typeof(Expression<Func<TTo, bool>>)) as Expression<Func<TTo, bool>>;
return _mapper.Map(from, type, typeof(Expression<Func<TTo, bool>>)) as Expression<Func<TTo, bool>>;
}
}
}
2 changes: 1 addition & 1 deletion version.props
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<Project>
<PropertyGroup>
<VersionPrefix>0.3.0</VersionPrefix>
<VersionPrefix>1.0.0</VersionPrefix>
</PropertyGroup>
</Project>

0 comments on commit 251df9e

Please sign in to comment.