【问题标题】:How to create custom class in ef codefirst model in asp.net web api如何在 asp.net web api 的 ef 代码优先模型中创建自定义类
【发布时间】:2012-10-27 10:36:52
【问题描述】:

我正在研究 asp.net web api。我在现有数据库中使用 EF 4.1 代码优先模型。我有一堂课,

public class Tab1
{
public int ID{get; set;}
public string FirstName{get; set;}
public string LastName{get; set;}
}

我已经创建了类似的 dbcontext,

public class EFBarContext:DbContext
    {
        public DbSet<Tab1> User{ get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            modelBuilder.Entity<Tab1>().ToTable("User");
        }
    }

首先我需要从表“用户”中获取所有记录,我需要根据名字和姓氏计算全名,我需要返回数据 json 格式,例如,

{"ID":212,"firstname":"kio","lastname":"nmk","fullname":"kionmk"}

为此,我创建了一个自定义类,例如,

public class Tab2:Tab1
{
public fullname{get; set;}
}

我用List&lt;Tab2&gt; 返回列表但我收到一个错误,如Schema specified is not valid error 0064: Facet 'MaxLength' must not be specified for type 'mediumtext'. 我已经关注了以下帖子,Class Inheritance with .NET EF4.1 + MySQL,但在我的情况下我无法弄清楚。所以请指导我。

【问题讨论】:

    标签: asp.net-mvc ef-code-first asp.net-web-api


    【解决方案1】:

    您的全名属性派生自名字和姓氏,因此我不会在数据库中创建单独的表来存储它(这就是您对 Tab2:Tab1 类所做的事情)。

    相反,您可以在 webapi 控制器中派生该字段:

    using (var context = new EFBarContext())
    {
        var jsonObject = context.User.Select(x => new {
            ID = x.ID,
            firstname = x.FirstName,
            lastname = x.LastName,
            fullname = string.Format("{0}{1}", x.FirstName, x.LastName),
        });
    }
    

    db中不需要单独继承的实体类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-14
      • 1970-01-01
      • 2017-11-29
      • 1970-01-01
      • 2011-08-13
      相关资源
      最近更新 更多