【问题标题】:how to assign enum to viewmodel property?如何将枚举分配给 viewmodel 属性?
【发布时间】:2014-07-12 13:06:34
【问题描述】:

主要课程:

public enum FooType
{
  Red,
  Green,
  Blue
}

public class Foo
{
  public int Id { get; set; }
  public FooType Type { get; set; }
  public string FooName { get; set; }
}

查看模型:

public class FooVM
{
  public FooType Type { get; set; }
  public string FooName { get; set; }
}

现在,我想使用 Linq 选择我想要的

_fooService.All().Select(x => new FooVM
             {
               FooName = x.FooName,
               Type = x.Type, // I'm having trouble with this guy. Says I cannot implicitly convert it.
              }
        );

我得到的错误是:

无法将类型“Namespace.Type”隐式转换为“Namespace.ViewModel.Type”。存在显式转换(您是否缺少演员表?)

我在转换它时遇到了问题。但我不知道应该做什么。我错过了什么?任何帮助将非常感激。谢谢

【问题讨论】:

  • 此 LINQ 查询在哪个集合上运行?
  • 我的错。我编辑了我的帖子。它运行在Foo
  • 同时发布完整错误。
  • 猜你是对的。您应该如何将 enum 分配给 ViewModel?
  • ..Name = x.Name..?? Foo 没有属性 Name(您的意思是 x.FooName

标签: c# asp.net-mvc linq enums


【解决方案1】:

该错误表明您在 2 个单独的命名空间中有一个名为 Type 的枚举,即使您具有相同的值,它们仍然不同。

namespace Namespace.Type
{
    public enum FooType
    {
        Red,
        Green,
        Blue
    }
}

namespace Namespace.ViewModel.Type
{
    public enum FooType
    {
        Red,
        Green,
        Blue
    }
}

如果底层整数值相同或每个枚举中的值顺序相同,您可以将一个枚举显式转换为int,并让另一个枚举从int 值隐式转换:

_fooService.All()
    .Select(x => new FooVM
    {
       FooName = x.FooName,
       Type = (int)x.Type,               
    });

【讨论】:

    【解决方案2】:

    您的错误消息表明您在NamespaceNamespace.ViewModels 中都定义了enum FooType,因此无法在它们之间进行隐式转换。我建议您从Namespace.ViewModels 中删除定义,并在Namespace.ViewModels 中包含对Namespace 的引用(使用语句)或按照Trevor 的建议转换类型

    【讨论】:

      【解决方案3】:

      您的查询没有问题。我刚刚测试了它。我会检查您的服务返回的实体。您可以在 LinqPad 中运行它。

      void Main()
      {
          //create test list
          var fooService = new List<Foo>();
          var random = new Random();
          Enumerable.Range(0,30).ToList().ForEach(i => fooService.Add(new Foo(){Id=i,Type=(FooType)random.Next(0,3),FooName="Foo"+i}));
      
          //select view models
          fooService.Select(x => new FooVM
                   {
                     FooName = x.FooName,
                     Type = x.Type
                    }
              ).Dump();
      }
      
      public enum FooType
      {
        Red,
        Green,
        Blue
      }
      
      public class Foo
      {
        public int Id { get; set; }
        public FooType Type { get; set; }
        public string FooName { get; set; }
      }
      
      public class FooVM
      {
        public FooType Type { get; set; }
        public string FooName { get; set; }
      }
      

      【讨论】:

        猜你喜欢
        • 2022-01-09
        • 1970-01-01
        • 2014-09-20
        • 1970-01-01
        • 2019-02-01
        • 2011-10-10
        • 1970-01-01
        • 2016-04-13
        • 1970-01-01
        相关资源
        最近更新 更多