简体   繁体   中英

Ef Core Select inherited Model

I have the following classes:

public class User{
    public Guid Id{get; set;}
    public string Name {get; set;}
}

public class TestUser : User{
    public string Title {get; set;}
}

public class CustomUser: User{
    public string Value {get; set;}
}

The configuration of the classes looks as follows:

modelBuilder.Entity<TestUser>().HasBaseType<User>();
modelBuilder.Entity<CustomUser>().HasBaseType<User>();

Each class is a seperate Database-Table (TPT).

each class has an DTO class that maps the data to share (UserGetDto, TestUserGetDto, CustomUserGetDto). The Dto-Classes are also inherited.

public class UserGetDto{}

public class TestUserGetDto : UserGetDto{}

public class CustomUserGetDto : UserGetDto{}

Now I want to select the DTOs using LINQ and return the respective DTO. But the switch-Case expression doesn't work:

public List<UserGetDto> GetUsers(){
    return _context.Users
        .Select(user => user switch{
            User usr when usr is TestUser => new TestUserGetDto(){
                ...
            },
            User usr when usr is CustomUser => new CustomUserGetDto(){ ... },
            _ => new UserGetDto(){...}
        }
        .ToList();
}

Is there any other way to select the respective DTOs?

Update

Experimenting with AutoMapper and referencing to the helpful comments, I found a working solution:

I added a UserProfile with the following Configuration:

CreateMap<User, UserGet>()
    .ConvertUsing(user => 
        user is TestUser ? new TestUserGet(){...}
        : user is CustomUser ? new CustomUserGet(){...}
        : new UserGet()
    );

My first tests seem to work as expected.

Disadvantage is, that I need to set eg TestUserDto manually.

Use Conditional operator instead:

public List<UserGetDto> GetUsers()
{
    return _context.Users
        .Select(user => 
            user is TestUser ? new TestUserGetDto()
            {
                Title = ((TestUser)user).Title
                ...
            }
            : user is CustomUser ? new CustomUserGetDto()
            {
                Value = ((CustomUser)user).Value
                 ... 
            },
            : new UserGetDto(){...}
        })
        .ToList();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM