Asp.net core 轻松获取模型到视图模型

Asp.net core 轻松获取模型到视图模型,asp.net-core,asp.net-core-mvc,Asp.net Core,Asp.net Core Mvc,我有这样一个视图模型: public class U1MyProfile1ViewModel : U1Profile { public List<SelectListItem> CountryList { get; set; } } 这可以编译,但我得到一个运行时错误: InvalidCastException:无法将类型为“WebApp.Models.U1Profile”的对象强制转换为类型为“WebApp.ViewModels.U1MyProfile1ViewModel

我有这样一个视图模型:

public class U1MyProfile1ViewModel : U1Profile
{
    public List<SelectListItem> CountryList { get; set; }
}
这可以编译,但我得到一个运行时错误:

InvalidCastException:无法将类型为“WebApp.Models.U1Profile”的对象强制转换为类型为“WebApp.ViewModels.U1MyProfile1ViewModel”

有什么办法可以轻松做到这一点吗?

比逐个字段将模型指定给视图模型更简单的操作。

如下所示设置视图模型:

查看模式

public class U1MyProfile1ViewModel
{
    public List<SelectListItem> CountryList { get; set; }
    public U1Profile U1Profile{get;set;}
    public string othervariable{get;set;}
}
最后,将viewmodal传递给View,您就得到了结果

要更好地理解,请参见下面的链接:


如果不想初始化代码,将代码> U1Prime<代码>映射到<代码> U1MyPrime1VIEWSMODS,那么您可以考虑使用--但是您仍然需要填充SelectListWhy,您继承了VIEWMET到模型?视图模型始终可以自由工作,不依赖任何东西。编辑数据时,视图模型不应包含数据模型-它破坏了使用视图模型的整体观点(关注点分离、防止过度发布攻击、防止发布不足攻击等)@StephenMuecke有意义。谢谢我们如何处理这个问题?
public class U1MyProfile1ViewModel
{
    public List<SelectListItem> CountryList { get; set; }
    public U1Profile U1Profile{get;set;}
    public string othervariable{get;set;}
}
var myProfile = await _mainDbContext.U1Profiles
            .AsNoTracking()
            .FirstOrDefaultAsync(i => i.SiteUserId == mySiteUserId);

        U1MyProfile1ViewModel myProfileViewModel = new U1MyProfile1ViewModel;
       U1MyProfile1ViewModel.U1Profile=myProfile;
       U1MyProfile1ViewModel.CountryList=yourcountrylist;