简体   繁体   English

ef Core Select 继承Model

[英]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).每个 class 都是一个单独的数据库表 (TPT)。

each class has an DTO class that maps the data to share (UserGetDto, TestUserGetDto, CustomUserGetDto).每个 class 都有一个 DTO class 映射要共享的数据(UserGetDto、TestUserGetDto、CustomUserGetDto)。 The Dto-Classes are also inherited. Dto-Classes 也是继承的。

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.现在我想 select 使用 LINQ 的 DTO 并返回相应的 DTO。 But the switch-Case expression doesn't work:但是 switch-Case 表达式不起作用:

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?有没有其他方法可以 select 各自的 DTO?

Update更新

Experimenting with AutoMapper and referencing to the helpful comments, I found a working solution:尝试使用 AutoMapper 并参考有用的评论,我找到了一个可行的解决方案:

I added a UserProfile with the following Configuration:我添加了一个具有以下配置的 UserProfile:

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.缺点是,我需要手动设置例如 TestUserDto。

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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