Hey guys, It's 5 am here, I was doing some code... when this came out:
public interface IViewModel { }
public interface IToViewModel<T> where T : IViewModel { }
public static class MvcExtensions
{
public static T ToViewModel<T>(this IToViewModel<T> self)
where T : IViewModel
{
var instance = Activator.CreateInstance<T>();
//this line just copys the properties with the same name from one object to another
self.Reflected().CopyMatchingPropertiesTo(instance /*destiny*/);
return instance;
}
}
My point with this code is do stuff like that:
public partial class UserInfo : IToViewModel<UserInfoViewModel> { }
public class UserInfoViewModel : IViewModel
{
[DisplayName("UserId")]
public Guid UserId { get; set; }
[DisplayName("User name")]
public string Username { get; set; }
[DisplayName("Email address")]
public string Email { get; set; }
}
public ActionResult Index(string username)
{
UserInfo userInfo = UserInfoHelper.Load(username);
UserInfoViewModel userInfoViewModel = userInfo.ToViewModel();
return View(userInfoViewModel);
}
Oks, this code runs ok, np.
But my question is about the uses of the interfaces...
My goal is convert a EntityFramework object into a ViewModel to use with ASP MVC views without doing to much parameters passing, i found in the interfaces a way to say what is each of the objects are, what they perform.
What looks weird to me is these interfaces with no method inside.
So what you guys think about it? Is there somewhere some cool blogpost/doc/etc about it? Do u have any idea how do it better? Should I go bed right now?
Other thing, .Net is bringing a lot of new ways of doing things... like linq, lambda, extension methods, expression trees... is there any study about "good practices" with these things?
I think that is huge, and makes your brain think different in the time that you are solving the problem... I would like to see what people are thinking/doing with that.
Thanks in advance