【问题标题】:restful c# page not display correctlyrestful c# 页面无法正确显示
【发布时间】:2018-03-19 08:41:54
【问题描述】:

我有一个控制器:

public IEnumerable<Food> Get()
{
    FoodDiaryContext cs = new FoodDiaryContext();
    var foodquery = cs.Foods.OrderByDescending(c => c.Description).ToList();

    return foodquery;
}

它应该显示:

{
    id:1
    description:food
    measure:[]
}

但我收到一个错误:

类型 'System.Data.Entity.DynamicProxies.Food_219DB877F13A4776536ADFD2AC86DB1FDBF0E8887DB7E9D658EFE7D9462C3BD5' 与数据合同名:预计不会 'Food_219DB877F13A4776536ADFD2AC86DB1FDBF0E8887DB7E9D658EFE7D9462C3BD5 http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies'。如果您使用 DataContractSerializer 或将任何静态未知的类型添加到已知类型列表中,请考虑使用 DataContractResolver - 例如,通过使用 KnownTypeAttribute 属性或将它们添加到传递给序列化程序的已知类型列表中。

public class Food
{
    public Food()
    {
        Measures = new List<Measure>();
    }

    public int Id { get; set; }
    public string Description { get; set; }
    public virtual ICollection<Measure> Measures { get; set; }
}

public class Measure
{
    public int Id { get; set; }
    public string Description { get; set; }
    public double Calories { get; set; }
    public double Fats { get; set; }
    public double Protein { get; set; }
    public double Carbohydrates { get; set; }
    public virtual Food Food { get; set; }
}

谁能告诉我我做错了什么?

谢谢

【问题讨论】:

  • 尝试在您的数据库上下文中禁用代理创建,这不是特定于 ASP.NET 的错误,并尝试更新您的上下文模型。
  • 您有什么特别的原因要将域模型返回给客户端吗?

标签: c# entity-framework asp.net-web-api


【解决方案1】:

感谢您的帮助。 我确实想要你的建议,而且它有效。

public class FoodDiaryContext:DbContext
    {
        public FoodDiaryContext()
        {
            this.Configuration.ProxyCreationEnabled = false;
        }

        public DbSet<Food> Foods { get; set; }
        public DbSet<Measure> Measures { get; set; }
    }

【讨论】:

    猜你喜欢
    • 2011-03-31
    • 2020-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-30
    相关资源
    最近更新 更多