具有内部设置器的OData属性-如UpdateDate [英] OData property with internal setter -- like UpdateDate

查看:58
本文介绍了具有内部设置器的OData属性-如UpdateDate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有动物"类的模型.
动物"类具有几个属性,但让我们关注以下属性:

I have a model with a class called "Animal".
The "Animal" class has several properties but let's focus on the following properties:

  1. 创建日期
  2. CreateUser

在动物"类中,我可以通过执行以下操作来使CreateDate工作:

In the "Animal" class I can get the CreateDate to work by doing the following:

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime CreateDate { get; set; }

这使我可以通过将数据库中的默认值设置为"GetDate()"来在数据库中生成CreateDate.
当外部调用者尝试在OData服务上设置" CreateDate字段时,它将忽略正在传递的数据.
这使它成为外部呼叫者的只读"属性.

This lets me generate the CreateDate in the database by setting the default value in the database as "GetDate()".
When an outside caller tries to "set" the CreateDate field on the OData service, it ignores the data being passed.
This makes it a "read only" property for outside callers.

除了需要在OData服务器上设置CreateUser = System.Threading.Thread.CurrentPrincipal.Identity.Name外,我需要执行与CreateUser类似的操作.

I need to do something similar to the CreateUser except I need to set the CreateUser = System.Threading.Thread.CurrentPrincipal.Identity.Name on the OData server.

如果我尝试私有集,则OData服务将完全不公开该属性.
如果我尝试公共设置,则外部呼叫者可以更改属性.
在动物"构造函数中,我设置了内部_CreateUser = System.Threading.Thread.CurrentPrincipal.Identity.Name

If I try a private set then the OData service does not expose the property at all.
If I try a public set then the outside caller can change the property.
In the "Animal" constructor I have set the internal _CreateUser = System.Threading.Thread.CurrentPrincipal.Identity.Name

我不确定如何在服务器端进行设置.

I'm not sure how to set it on the server side.

推荐答案

这就是我要做的工作.

在模型中,我有以下内容:

In the model I have the following:

public string CreateUser { get; set; }

[NotMapped]
public string CreateUserName
{
    get
    {
        return CreateUser;
    }
    set
    {
        CreateUser = CreateUser ?? System.Threading.Thread.CurrentPrincipal.Identity.Name;
    }
}

然后在WebApiConfig中,我有以下内容:

And then in the WebApiConfig I had the following:

builder.EntitySet<Animal>("Animals"));
builder.EntityType<Animal>().Ignore(p => p.CreateUser); // hide CreateUser
builder.StructuralTypes.First(t => t.ClrType == typeof(Animal))
    .AddProperty(typeof(Animal).GetProperty(nameof(Animal.CreateUserName))); // show CreateUserName

这篇关于具有内部设置器的OData属性-如UpdateDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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