简体   繁体   English

实体框架通过关系发布到POCO

[英]Entity Framework Post to POCO with relationship

I have a C# program on the entity framework using mvc4. 我在使用mvc4的实体框架上有一个C#程序。

I was wondering if it was possible (which I am sure it is) to have C# do the automatic binding of a post to an object that has a relation. 我想知道是否有可能(我确定是)让C#将帖子自动绑定到具有关系的对象。

Ex: I have an Item class, that has a relationship with the User class: 例如:我有一个Item类,它与User类有关系:

public class Item
{
    public int ItemId{get;set;}
    public string Name{get;set;}

    public virtual User Owner{get;set;}
}

I have an ItemController with a post method: 我有一个带post方法的ItemController:

public class ItemController
{
    ...
    public HttpResponseMessage PostItem(Item item)
    {
         ....
    }
}

How does posting and dynamic binding work with classes that have relations? 发布和动态绑定如何与具有关系的类一起使用?

Yes, it's possible. 是的,有可能。 But you should never (well, almost never) post directly to EF models. 但是,您永远都不要(很好,几乎永远不要)直接发布到EF模型。 The reasons are many, but security is high on the list, but maintainability and (separation of concerns, for instance) is also very high. 原因很多,但安全性高,但是可维护性和(例如,关注点分离)也非常高。

How can it be a security problem? 怎么可能是安全问题? Let's say your User property has a field "IsAdmin", even if you do not have any reference to IsAdmin in your view, a malicious user could post an Owner.IsAdmin of true and if you SaveChanges, your user is now an administrator. 假设您的User属性的字段为“ IsAdmin”,即使您在视图中没有任何对IsAdmin的引用,恶意用户也可能将Owner.IsAdmin发布为true,如果您保存了Change,则您的用户现在是管理员。

Yes, it's true, your app may not work that way. 是的,的确如此,您的应用程序可能无法正常运行。 But other details could be hacked, maybe passwords changed, or any number of other possible ways to be malicious. 但是其他细节可能会被黑客入侵,密码可能会更改或其他许多可能的恶意方式。

As a rule, just do not ever pass your data models directly to the view. 通常,永远不要将数据模型直接传递给视图。 Use an intermediate view model, and copy only the authorized values between, and only have the fields necessary for the view in the view model. 使用中间视图模型,并且仅在它们之间复制授权值,并且仅在视图模型中具有视图所需的字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM