efcore icon indicating copy to clipboard operation
efcore copied to clipboard

EFCore uses default values when projecting to dto with FirstOrDefault

Open bmarder opened this issue 8 years ago • 2 comments

Pardon the title, it's a bit hard to describe this scenario. I'm doing a projection of a model along with the FirstOrDefault() of one of it's children, and attempt to map a get only property that is always set to true. EFCore does not throw any error, but it ignores the getter logic of the Blog model and just maps the IsActive property on the dto to false.

If I just change the BlogDto to have an array of posts instead, and just map all the posts instead of FirstOrDefault(), then it works as expected.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

using AutoMapper;
using AutoMapper.QueryableExtensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;

namespace EFCoreBugs
{
    class Program
    {
        static async Task Main(string[] args)
        {
            Mapper.Initialize(x =>
            {
                x.AddProfile<BlogProfile>();
                x.AddProfile<PostProfile>();
            });

            using (var db = new TestDb())
            {
                await db.Database.EnsureDeletedAsync();
                await db.Database.EnsureCreatedAsync();

                var blog = new Blog();
                db.Blogs.Add(blog);
                await db.SaveChangesAsync();
            }
            using (var db = new TestDb())
            {
                var blogs = await db.Blogs
                    .ProjectTo<BlogDto>(Mapper.Instance.ConfigurationProvider)
                    .ToListAsync();

                // expected true, actual false
                Console.WriteLine(blogs.First().IsActive);
            }
            
            Console.ReadLine();
        }
    }

    public class TestDb : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
        public DbSet<Post> Posts { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            var log = new LoggerFactory(new[] { new ConsoleLoggerProvider((_, __) => true, true) });
            optionsBuilder.UseLoggerFactory(log);
            optionsBuilder.UseSqlServer("Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=master;Database=bugtest;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
        }
    }

    public class Blog
    {
        public Guid Id { get; set; }

        [InverseProperty(nameof(Post.Blog))]
        public virtual List<Post> Posts { get; } = new List<Post>();

        [NotMapped]
        public bool IsActive => true;

    }
    public class Post
    {
        public Guid Id { get; set; }
        public Guid BlogId { get; set; }

        [NotMapped]
        public bool IsActive => true;

        [ForeignKey(nameof(BlogId))]
        public virtual Blog Blog { get; private set; }
    }

    public class Para
    {
        public Guid Id { get; set; }
        public Guid PostId { get; set; }

        [ForeignKey(nameof(PostId))]
        public virtual Post Post { get; private set; }
    }

    public class BlogDto
    {
        public bool IsActive { get; set; }
        public int Foo { get; set; }
        public PostDto Post { get; set; }
        //public IEnumerable<PostDto> Posts { get; set; }
    }
    public class PostDto { }

    public class BlogProfile : Profile
    {
        public BlogProfile()
        {
            CreateMap<Blog, BlogDto>()
                .ForMember(x => x.IsActive, x => x.MapFrom(y => y.IsActive))
                //.ForMember(x => x.Posts, x => x.MapFrom(y => y.Posts));
                .ForMember(x => x.Post, x => x.MapFrom(y => y.Posts.FirstOrDefault()));
        }
    }
    public class PostProfile : Profile
    {
        public PostProfile()
        {
            CreateMap<Post, PostDto>();
        }
    }
}

Further technical details

EF Core version: 2.1.0-preview2-final Database Provider: Microsoft.EntityFrameworkCore.SqlServer Operating system: win10 x64 IDE: Visual Studio Community 2017 Preview 15.8.0 Preview 1.1

bmarder avatar May 26 '18 18:05 bmarder

I am unable to reproduce this in the absence of AutoMapper. Seems like there is something wrong with automapper configuration. Please provide us a repro which uses only EF and no automapper for us to investigate.

smitpatel avatar May 31 '18 18:05 smitpatel

@smitpatel You are definitely right. I just tried to replicate this with version 7.0.0-alpha-0001 of automapper and now it works. I was previously using version 6.2.2 of automapper

bmarder avatar Jun 01 '18 13:06 bmarder