Razor proxy type error. System.Data.Entity.DynamicProxies

眉间皱痕 提交于 2019-12-19 10:04:44

问题


I have a class User and then another Type UserSpecial with some special user properties. I pass it in razor to the partial method class to create the UserSpecial form which expects an object of type User Special but i get an error.

@model User
    @using (Html.BeginForm())
    { 

        @Html.ValidationSummary(true)
        <fieldset>
            @Html.Partial("../UserSpecial/_CreateOrEdit", Model.UserSpecial)
            <p class="submit clear">
                <input type="submit" value="Register" />
            </p>
        </fieldset>
    }
</div>

Error i get -

The model item passed into the dictionary is of type 'System.Data.Entity.DynamicProxies.User_AC9DED50C9495788046D6BFA3B90DDFC6AD2884157CF23C91FCB3B7A55F70B18', but this dictionary requires a model item of type 'UserSpecial'.

What am i doing wrong here?

From my controller i just pass the current User Object that i have stored in the session state.

Controller -

 public ActionResult Register()
        {
            return View(userRepository.Current);
        }

Here Current is of type "User"

Model -

public partial class User
    {
        public User()
        {
        }

        public int UserID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Sex { get; set; }
        public System.DateTime CreateDate { get; set; }
        public string Email { get; set; }
        public string HomeTown { get; set; }
        public short UserType { get; set; }

        public virtual UserSpecial UserSpecial { get; set; }
    }

Model Declaration for _CreateOrEdit is

@model UserSpecial

回答1:


No idea what userRepository.Current is but it seems that it doesn't correctly/eagerly load the UserSpecial property. Why don't you use view models? Why are you passing domain entity models to your views? That's bad practice. You should define view models that contain only the data that's required by your view and then in your controller action map between your domain models and the corresponding view model which will be passed to the view.




回答2:


The solution for this issue is pretty simple:

You should just use a wrapper class (view model) as Darin suggested.

So for example:

(entity domain model):

public class MyEntityModel
{
    public int Id { get; set; }
    public String Name { get; set; }
}

=> put it in a ViewModel (just a stupid wrapper) should result in this

public class MyViewModel
{
    public MyEntityModel MyEntityModel { get; set; }
}

Now, in the view, u should be able to access the "name" property by doing this

<div>
    The entity object's name is "@model.MyEntityModel.Name"
</div>

(notice you should not use @model.Name!)



来源:https://stackoverflow.com/questions/7392022/razor-proxy-type-error-system-data-entity-dynamicproxies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!