简体   繁体   中英

How can i fill a value from one my domain model to my edit model?

In my project i have : countries and CountryEditModel .

public class countries
{
     public int id { get; set; }
     public string Code { get; set; }
     public string Name { get; set; }
}

public class CountryEditModel
{
     public int id { get; set; }
     public string Code { get; set; }
     public string Name { get; set; }
     public bool isvalid{ get;set; }
}

countries is my domain model which is binded with entity framework and countryEditModel is the model which i use in my views.
How can i fill values from countries to countryEditModel . I actually want to bind list of all countries to dropdownlist in my view and I don't want to use my countries domain model directly in my view.

To solve i have done this

var countryDomain = context.Country.Select(c => c).ToList();
var countrylist = new List<CountryEditModel>();
var countrymodel = new CountryEditModel();
foreach (var country in countryDomain)
countrymodel = new CountryEditModel()
 {
   Code = country.Code,
   Name = country.Name,
   id = country.id
 };

countrylist.Add(countrymodel);

Is there any better way?

Answer:
Actually this is what i exactly wanted to do

 var countryViewModel = context.Country.Select(c => new CountryEditModel
                {
                    Code = c.Code,
                    Name = c.Name,
                    id = c.id
                }).ToList();

As indicated by the @rohitsingh this is what he exactly wanted to do

var countryViewModel = context.Country.Select(c => new CountryEditModel
    {
        Code = c.Code,
        Name = c.Name,
        id = c.id
    }).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