开发者

MVC Model Confusion

I have confusion regarding models when we have relations between multiple tables. Formerly, I was using views or stored procedures of SQL to manipulate data but now I am using Entity Framework so confused how my model should look like ?

I have a table for Users, UserImages, UserRoles.

UserImages and UserRoles is referring to UserID from Users table.I am not sure how my model should be. While displaying data I generally use a view created in SQL server by joining these 2 tables. And when an user is edited or creat开发者_C百科ed I update these 3 tables.

Not sure what should my model look like in this case ? Do I create a SQL server view and add it to edmx ? Or add 3 tables separately in EDMX and create custom properties in User model for those other 2 tables?

[HttpPost] public ActionResult Create(UserFormViewModel UserView) {

        User user = UserView.User;

        try {

            if (ModelState.IsValid) {
                repository.AddUser(user);
                repository.Save();

                return View(new UserFormViewModel(user));
            } else {
                return View(new UserFormViewModel(user));
            }
        } catch (Exception ex) {
            ModelState.AddModelError("Error", ex.Message);
            return View(new UserFormViewModel(user));
        }
    }





public class UserFormViewModel {

    UucsrRepository repository = new UucsrRepository();

    public User User { get; private set; }
    public SelectList States { get; private set; }
    public SelectList Genders { get; private set; }
    public SelectList RolesLists { get; private set; }
    public SelectList SelectedRolesLists{ get; private set; }

    public UserFormViewModel(User contact) {
        User = contact;
        States = new SelectList(repository.GetAllStates() ,"ShortName","Name");
        Genders = new SelectList(repository.GetAllGenders(), "Gender", "Description");
        RolesLists = new SelectList(repository.GetAllRolesLists(), "Id", "Name");
    }
}

I am not sure how should I exactly handle the Adding role list and images here .


The User class should have a list of Roles and Images. The tables should have foreign keys to each other by UserId. When generating the models from your tables select all the tables you want Entity Framework to use. The User model should in that case automatically have a List of UserRoles and UserImages. Change the names appropriately. When adding or changing roles or images you should fetch the user and update or add them to the correct list. That's how I would do it. In this case your User is an aggregate root. Check out DDD you're interested.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜