Skip to content

Instantly share code, notes, and snippets.

@jenseralmeida
Last active July 15, 2019 22:36
Show Gist options
  • Save jenseralmeida/a51b55b2eb5d1e42a5ebd3e0ef2bd269 to your computer and use it in GitHub Desktop.
Save jenseralmeida/a51b55b2eb5d1e42a5ebd3e0ef2bd269 to your computer and use it in GitHub Desktop.
JonPSmith/EfCore.GenericServices Read-only entity properties causes null exception (https://github.com/JonPSmith/EfCore.GenericServices/issues/30)
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<RootNamespace>readonly_property</RootNamespace>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="EFCore.GenericServices" Version="2.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="2.2.6" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="xunit" Version="2.4.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.0" />
</ItemGroup>
</Project>
using GenericServices;
using GenericServices.Setup;
using Microsoft.EntityFrameworkCore;
using Xunit;
namespace readonly_property
{
public class UnitTest1
{
[Fact]
public void Dto_with_non_writable_property_causes_null_exception()
{
using (var context = new SomeContext(InMemoryOptions.Create<SomeContext>()))
context.SetupSingleDtoAndEntities<ImutableDto>();
}
private static class InMemoryOptions
{
public static DbContextOptions<T> Create<T>(string databaseName = "InMemory") where T: DbContext
=> new DbContextOptionsBuilder<T>()
.UseInMemoryDatabase(databaseName: databaseName)
.Options;
}
}
public class SomeContext : DbContext
{
public SomeContext(DbContextOptions<SomeContext> options): base(options) { }
public DbSet<ImutableEntity> Entities { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<ImutableEntity>().Property(e => e.Id).ValueGeneratedNever();
builder.Entity<ImutableEntity>().Property(e => e.Name);
}
}
public class ImutableEntity
{
public ImutableEntity(int id, string name)
{
Id = id;
Name = name;
}
public int Id { get; private set; }
public string Name { get; private set; }
}
public class ImutableDto: ILinkToEntity<ImutableEntity>
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment