开发者

ASP.NET MVC display class content with a dropdown

In my NHIbernate (Database Model) I have this :

public class Pers {
    public int Id{ get; set ;}
    public string FirstName{ get; set ;}
    public string LastName{ get;开发者_JAVA百科 set ;}
    public string City{ get; set ;}
    public int Age{ get; set ;}

    public Role Role{ get; set ;}
}

I have some dropwon (Database mode) :

public class Role {
    public int Id{ get; set ;}
    public string NL{ get; set ;}
    public string FR{ get; set ;}
}

In my view I'd like use the dropdown and display some record (not all, in my real class there are much more properties) of Pers. I created a Dto class for Pers with the fields I need :

public class PersDto {
    public int Id{ get; set ;}
    public string FirstName{ get; set ;}
    public string LastName{ get; set ;}

    public RoleDto RoleDto{ get; set ;}
}

public class RoleDto {
    public int Id{ get; set ;}
    public string NL{ get; set ;}
    public string FR{ get; set ;}
}

In the controller :

Mapper.CreateMap<Role, RoleDto>();
myModel.RoleDto = Mapper.Map<Role, RoleDto>(roleListFromDB);

Mapper.CreateMap<Pers, PersDto>();
myModel.PersDto = Mapper.Map<Pers, PersDto>(persFromDB);

public class MyModel{
    public PersDto PersDto{ get; set ;}
    public RoleDto RoleDto{ get; set ;}
}

Is it the right way ? Or it's better to do this with creating a PersDto:

public class MyModel{
    public string FirstName{ get; set ;}
    public string LastName{ get; set ;} 
    public RoleDto RoleDto{ get; set ;}
}

Is it possible with automapper to copy only some fields and not all ?

Thanks,


Is it the right way ?

No, you should not call Mapper.CreateMap<TSource, TDest> in the controller. This method should be invoked only once for the entire lifetime of the AppDomain, ideally in Application_Start.

You could write a mapping profile:

public class PersonProfile : Profile
{
    protected override void Configure()
    {
        Mapper.CreateMap<Role, RoleDto>();
        Mapper.CreateMap<Pers, PersDto>();
    }
}

then in Application_Start configure those profiles:

Mapper.AddProfile(new PersonProfile());

and finally in your controller only use the Mapper.Map<TSource, TDest> method:

var myModel = new MyModel();
myModel.RoleDto = Mapper.Map<Role, RoleDto>(roleListFromDB);
myModel.PersDto = Mapper.Map<Pers, PersDto>(persFromDB);
return View(myModel);


If your global.asax gets too big, you can always split the Commands to execute at startup into other classes/methods, and use the Command pattern to invoke them from Global; to include mapping.

We use a separate mapping file for our mappings, and when we want to ignore a property, we use the ignore method on AutoMapper.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜