2012-10-27 49 views
0

我正在處理asp.net web api。我正在使用現有數據庫的EF 4.1代碼優先模型。我有一個類一樣,如何在asp.net web api中的ef codefirst模型中創建自定義類

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<Tab2>列表中,但我得到了如下的錯誤Schema specified is not valid error 0064: Facet 'MaxLength' must not be specified for type 'mediumtext'. 我按照下面的帖子,Class Inheritance with .NET EF4.1 + MySQL但我不能算出它在我的處境。所以請指導我。

回答

0

您的全名屬性是從名字和姓氏派生的,所以我不會在數據庫中創建一個單獨的表來存儲它(這就是您在使用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單獨繼承實體類。

相關問題