开发者

Pass variable model type to C# function in MVC to simplfy code

开发者 https://www.devze.com 2023-03-13 19:02 出处:网络
I have a bunch of model update routines that only vary with the model passed, for example: public void UpdateAccount(AccountViewModel model)

I have a bunch of model update routines that only vary with the model passed, for example:

public void UpdateAccount(AccountViewModel model)
{
    var _currentData = (from data in db.Accounts
                         where data.AccountId == model.AccountId
                         select data).Single();
    开发者_JAVA技巧Mapper.Map(model, _currentData);
    Save();
}

I have a bunch of similar functions, where the model passed varies along with the data key. Can this be made more generic?


One option is to make each of your models implement the same interface:

interface IViewModel
{
    int AccountId { get; }
}

class AccountViewModel : IViewModel
{
    ...
}

And then you can pass any viewmodel implementing this interface to your UpdateAccount method:

public void UpdateAccount(IViewModel model)
{
    var _currentData = (from data in db.Accounts
                        where data.AccountId == model.AccountId
                        select data).Single();
    Mapper.Map(model, _currentData);
    Save();

}

Or you could define it as:

public void UpdateAccount<TViewModel>(TViewModel model) 
    where TViewModel: IViewModel { ... }

However, this means you will also have to change the definition of Mapper.Map(...) method to accept your new interface: Mapper.Map(IViewModel model, ...).

Edit: Just saw each viewmodel has a different data key (property?), perhaps this is a better solution:

public void UpdateAccount<T>(T model, Func<T, int> dataKeySelector)
{
    var _currentData = (from data in db.Accounts
                        where data.AccountID == dataKeySelector(model)
                        select data).Single();
    Mapper.Map(model, _currentData);
    Save();
}   

Which can be called by UpdateAccount(model, m => m.AccountID);.

Hope this helps.

0

精彩评论

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