0

I am having a base model and a view model derived from it.

Base Model

public class Feed
{
public int Id { get; set; }
public string Name { get; set; }
public string Url { get; set; }
}

Derived Model

public class FeedViewModel :  Feed
{
   public bool EditMode { get; set; }    
}

Data Access Layer

public Feed GetFeed(){
   --db code to retreive all feed
}

Controller

public FeedController : Controller
{
   public ActionResult Index()
   {
        var data = DAL.GetFeed();
        var model = new FeedViewModel{ EditMode = true };

         model.Id = data.Id;
         model.Name = data.Name;
         model.Url = data.Url;   //This is working

       //But i dont want like this, coz i cant reassign all the proerties again. Is there any other easy way like this
        model = (FeedViewModel)data;
    } 
 }

I dont want to reassign all the properties values again to derived model. Instead i am looking for any other easy way? Any ideas?

4

2 回答 2

2

我建议使用组合而不是继承:

public class FeedViewModel
{
    public bool EditMode { get; set; }    
    public Feed Feed { get; set; }
}

然后:

var data = DAL.GetFeed();
var model = new FeedViewModel { EditMode = true, Feed = data };

从根本上说,我不希望视图模型与它作为视图模型的模型相同 - 我希望能够使用该模型,但我不希望对其使用继承。

如果您愿意,视图模型可以通过委托公开视图的属性 - 可能带有属性更改通知。

编辑:另一种选择(也可能不适用——我们不知道你可以在这个项目中改变多少)是让你的GetFeed方法在 DAL 中通用:

public Feed GetFeed<T>() where T : Feed, new()
{
   --db code to retreive all feed
}

然后你可以调用它:

var model = DAL.GetFeed<FeedViewModel>();
model.EditMode = true;
于 2013-05-03T13:20:00.673 回答
0

使用自动映射器。

像这样创建一个AutoMapperConfig类:

public class AutoMapperConfig
{
    public static void CreateMaps()
    {
        // Feed domain / view model mappings
        Mapper.CreateMap<FeedViewModel, Feed>()
        Mapper.CreateMap<Feed, FeedViewModel>();            
    }
}

在应用程序启动时调用您的CreateMaps()方法Global.asax以注册映射。

现在,您Action需要做的就是:

public FeedController : Controller
{
   public ActionResult Index()
   {
        var data = DAL.GetFeed();
        var model = Mapper.Map<Feed, FeedViewModel>(data);
        model.EditMode = true;

        return View(model)
    } 
 }

然后在其他一些操作中,您只需反转该过程

[HttpPost]
public ActionResult SomeOtherAction()
{
    FeedViewModel model = new FeedViewModel();
    TryUpdateModel(model);

    if (ModelState.IsValid)
    {
        var feed = Mapper.Map<FeedViewModel, Feed>(model);
        DAL.UpdateFeed(feed);
    }

    return View(model)
}
于 2013-05-03T13:56:02.743 回答