简体   繁体   English

如何在Entity Framework的此枚举上创建Get方法?

[英]How to make a Get method on this enums on Entity Framework?

I have in my enum this: 我在枚举中有以下内容:

namespace MyServer.Aluno.Model
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using System.ComponentModel.DataAnnotations;

    public enum AlunoSexo
    {
        [Display(Name = "Masculino")]
        M = 1,

        [Display(Name = "Feminino")]
        F = 2,
    }
}

How to make HttpGet to display it on Json in my api? 如何使HttpGet在我的api中的Json上显示它?

You can use this function: 您可以使用此功能:

public class EnumModel<T>
{
    public string StringValue { get; set; }
    public T EnumValue { get; set; }
    public int IntValue { get; set; }
    public string DisplayName { get; set; }
    public static List<EnumModel<T>> GetModel()
    {
        var t = typeof(T);
        var fields = t.GetFields();
        return  fields.Where(x => x.CustomAttributes.Any(z => z.NamedArguments.Any(n => n.MemberName == "Name"))).Select(x =>
        new EnumModel<T>
        {
            StringValue = x.Name,
            EnumValue = (T)Enum.Parse(t, x.Name),
            IntValue = (int)Enum.Parse(t, x.Name),
            DisplayName = (string)x.CustomAttributes.Select(z => z.NamedArguments.First(n => n.MemberName == "Name").TypedValue).First().Value,


        }).ToList();
    }
}

Usage: 用法:

var modelList = EnumModel<AlunoSexo>.GetModel();
string json = new JavaScriptSerializer().Serialize(modelList);
return new View(ModelList);

Your JSON will look like this: 您的JSON将如下所示:

[
   {
      "StringValue":"M",
      "EnumValue":1,
      "IntValue":1,
      "DisplayName":"Masculino"
   },
   {
      "StringValue":"F",
      "EnumValue":2,
      "IntValue":2,
      "DisplayName":"Feminino"
   }
]

Alternatively you can use a custom library for your Javascript Serialization like Newtonsoft.Json and change the way you decorate your enum to work that library. 另外,您可以为Javascript序列化使用自定义库,例如Newtonsoft.Json并更改装饰enum的方式以使用该库。

A couple examples of that here: How to tell JSON.NET StringEnumConverter to take DisplayName? 这里有几个示例: 如何告诉JSON.NET StringEnumConverter接受DisplayName?

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

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