可以在实体模型中使用私有设置器吗? [英] Can private setters be used in an entity model?

查看:101
本文介绍了可以在实体模型中使用私有设置器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚从Entity Framework开始,我担心主键可以被覆盖的轻松。我知道我可以在我的控制器中保护这个模型(我在ASP.NET MVC 5中使用WebAPI),但是我想知道是否有可能阻止任何人通过注释或其他东西从模型本身设置我的模型的ID?

I'm just starting out with Entity Framework and I'm concerned about the ease with which a primary key can be overridden. I know I can protect this model in my controller (I'm using WebAPI with ASP.NET MVC 5), but I am wondering if it is possible to prevent anyone setting the ID of my model from the model itself via annotations or something?

基本上我可以这样做:

public int ID { get; private set; }

或类似的东西?

如果通过Google很容易找到,那么我不知道要搜索的条款。我没有找到任何真正回答这个问题的东西。

If this is easily found through Google then I don't know the terms to search. I've not been able to find anything that really answers this.

推荐答案

是的,可以,它应该可以正常工作。按照这篇博文由Julie Lerman(谁是Microsoft的实体框架MVP,所以我强烈建议您通过EF阅读她的博客!):

Yes you can, and it should work just fine. Per this blog post by Julie Lerman (who's Microsoft's Entity Framework MVP, so I highly recommend that you read her blog on your journey through EF!):


实体框架需要无参数构造函数为了
实现从查询返回的对象(或加载)。我已经在课堂上赚了
这个让步,但注意到它是一个私人的
构造函数。所以我还在保护我的课。没有人可以访问它。
但是当我执行查询时,EF仍然可以填充这个类。
不,我没有做一些魔术来告诉EF使用我的public
构造函数。它真的使用私有构造函数。

Entity Framework requires a parameterless constructor in order to materialize objects returned from queries (or loading). I have made this concession in my class but notice that it is a private constructor. So I’m still protecting my class. Nobody can access it. But EF is still able to populate this class when I execute queries. And no, I’m not doing some magic to tell EF to use my public constructor. It really uses the private constructor.

这篇关于可以在实体模型中使用私有设置器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆