将参数传递给ViewModel的重载构造函数

时间:2018-12-26 00:04:55

标签: c# constructor overloading viewmodel

我的控制器中有一个ViewModel的创建者,我想知道-如何简化它?我当时正在考虑将此代码移到我的视图模型中,并制作一个可以填充它的重载构造函数,但是将参数传递给视图模型是否正确?据我所知,我应该避免将参数传递给视图模型。还是当我们谈论重载的构造函数时好吗?

public CountryViewModel CreateViewModel(List<Country> countries)
    {
        CountryViewModel flags = new CountryViewModel();

        flags.Countries = countries;
        flags.CountriesCount = countries.Count;
        flags.EuropeanCountriesCount = countryService.GetContinentCount("Europe", countries);
        flags.AsianCountriesCount = countryService.GetContinentCount("Asia", countries);
        flags.AfricanCountriesCount = countryService.GetContinentCount("Africa", countries);
        flags.SAmericanCountriesCount = countryService.GetContinentCount("South America", countries);
        flags.NAmericanCountriesCount = countryService.GetContinentCount("North America", countries);
        flags.AustralianCountriesCount = countryService.GetContinentCount("Australia", countries);
        flags.CountriesArea = countryService.GetCountriesArea(countries).ToString("N0");
        flags.CountriesPercent = countryService.CountCountriesPercent(flags.CountriesCount);
        flags.CountriesAreaPercent = countryService.CountCountriesAreaPercent(countryService.GetCountriesArea(countries));
        flags.ShareLink = "?id=" + sharingService.GenerateGuid();

        return flags;
    }

2 个答案:

答案 0 :(得分:0)

我将使用扩展方法进行模型转换,让代码简化而不是重载构造函数。

public static class ViewModelExtension{

    public static CountryViewModel CreateViewModel(this List<Country> countries){

        var countryService = new CountryService();

        CountryViewModel flags = new CountryViewModel();
        flags.Countries = countries;
        flags.CountriesCount = countries.Count;
        flags.EuropeanCountriesCount = countryService.GetContinentCount("Europe", countries);
        flags.AsianCountriesCount = countryService.GetContinentCount("Asia", countries);
        flags.AfricanCountriesCount = countryService.GetContinentCount("Africa", countries);
        flags.SAmericanCountriesCount = countryService.GetContinentCount("South America", countries);
        flags.NAmericanCountriesCount = countryService.GetContinentCount("North America", countries);
        flags.AustralianCountriesCount = countryService.GetContinentCount("Australia", countries);
        flags.CountriesArea = countryService.GetCountriesArea(countries).ToString("N0");
        flags.CountriesPercent = countryService.CountCountriesPercent(flags.CountriesCount);
        flags.CountriesAreaPercent = countryService.CountCountriesAreaPercent(countryService.GetCountriesArea(countries));
        flags.ShareLink = "?id=" + sharingService.GenerateGuid();

        return flags;
    }
}

在控制器中像这样使用。

var viewModel = countries.CreateViewModel();

或者我可以尝试使用nested resources的另一种方式,该框架对于在类之间传输数据非常有用。

答案 1 :(得分:0)

我建议不要将其放在视图模型中。您的代码正在调用各种服务并将结果汇​​总在一起。这是编排逻辑,实际上可能属于控制器或其他服务。