[英]Web Api2 and protected setters?
I've got an entity which I pull directly from the database using EF that looks like this: 我有一个实体,可以使用EF直接从数据库中提取它,如下所示:
public class MyEntity : EntityBase {
public string MyProperty { get; set; }
}
where as EntityBase
looks like the following 其中
EntityBase
如下所示
public abstract class EntityBase {
public int Id { get; protected set; }
}
The reason the Id
is protected is simple: It shouldn't be changed at any state. 保护
Id
的原因很简单:在任何状态下都不应更改。 This works fine with EF (I assume it uses reflection to set the value?), however when I send a POST
from a client with the model data via my web api, the Id
is always 0 (default). 这对于EF可以正常工作(我假设它使用反射来设置值吗?),但是当我通过网络api从客户端发送带有模型数据的
POST
时, Id
始终为0(默认值)。 Is there a way to access protected setters with Web API 2? 是否可以使用Web API 2访问受保护的设置器? Or do I have to map it manually from a DTO?
还是我必须从DTO手动映射它?
When your client tries to create a MyEntity it should know nothing about id since it's not relevant at creation state. 当您的客户端尝试创建MyEntity时,它应该对id一无所知,因为它与创建状态无关。 It just knows that new entity will have MyProperty set to "some value".
它只知道新实体会将MyProperty设置为“某些值”。 I prefer to work with dto and they should contain only request related information.
我更喜欢使用dto,它们应该只包含与请求相关的信息。
For mapping I'd suggest to use AutoMapper . 对于映射,我建议使用AutoMapper 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.