编程方式打开的属性序列化.NET的EF code首先 [英] Programatically turn on properties serialization on .NET EF Code First
问题描述
我与$ EF上仿照6 C $ cFirst我的数据。
我建立一个Web API来将有机会获得其客户不同类型的,但取决于client's配置他们应该看到与否模型的某些属性。
I have my data modeled with CodeFirst on EF 6. I'm building a Web API to which different type of clients would have access but depending on the client´s configuration they should see or not certain properties of the models.
¿如何打开或关闭 [JsonIgnore]
或 [连载]
?是否有可能设置一组特定的规则,要做到这一点,就像一个验证?
¿How do I turn on or off the [JsonIgnore]
or [serialized]
? Is it possible to set a certain set of rules to do this, like a validator?
推荐答案
您可以创建自定义的合同解析器和创建响应时使用它:
Option 1: Using a custom ContractResolver
You can create a custom contract resolver and use it when creating the response:
public class TestContractResolver : DefaultContractResolver
{
public string ExcludeProperties { get; set; }
protected override IList<JsonProperty> CreateProperties(Type type,
MemberSerialization memberSerialization)
{
if (!string.IsNullOrEmpty(ExcludeProperties))
return base.CreateProperties(type, memberSerialization)
.Where(x => !ExcludeProperties.Split(',').Contains(x.PropertyName))
.ToList();
return base.CreateProperties(type, memberSerialization);
}
}
这里的用法:
[HttpGet]
public HttpResponseMessage Test()
{
var person = new Person() { Id = 1, FirstName = "x", LastName = "y", Age = 20 };
string excludeProperties= "FirstName,Age";
string result = JsonConvert.SerializeObject(person, Formatting.None,
new JsonSerializerSettings
{
ContractResolver = new TestContractResolver()
{
ExcludeProperties = excludeProperties
}
});
var response = this.Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(result, Encoding.UTF8, "application/json");
return response;
}
和结果将是:
{"Id":1,"LastName":"y"}
选项2:使用字典
您可以用逗号分隔的属性名的字符串忽略,然后选择属性,并把它们(名称和值),在字典中,并用它们作为结果是:
Option 2: Using Dictionary
You can have a comma separated string of property names to ignore, then select properties and put them (name and value) in a dictionary and use them as result:
[HttpGet]
public Dictionary<string, Object> Test()
{
var person = new Person() { Id = 1, FirstName = "x", LastName = "y", Age = 20 };
string excludeProperties = "FirstName,Age";
var dictionary = new Dictionary<string, Object>();
person.GetType().GetProperties()
.Where(x => !excludeProperties.Split(',').Contains(x.Name)).ToList()
.ForEach(p =>
{
var key = p.Name;
var value = p.GetValue(person);
dictionary.Add(key, value);
});
return dictionary;
}
和结果将是:
{"Id":1,"LastName":"y"}
这篇关于编程方式打开的属性序列化.NET的EF code首先的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!