1

我嘗試使用實體框架代碼優先使用MVC 3中的新腳手架功能。我的模型是這樣的:在ASP.NET MVC 3和實體框架中使用繼承的腳手架模型

public abstract class A 
{ 
    public int Id { get; set; } 
} 

public class B : A 
{ 
    public string Name { get; set; } 
} 

public class MyContext : DbContext 
{ 
    public DbSet<A> As { get; set; } 
} 

我使用MVC新控制器嚮導來創建一個新的控制器,並選擇支架類型A. CRUD代碼生成,我可以成功啓動在網頁瀏覽器項目。當我嘗試創建一個新的A,我得到了以下錯誤消息:

「不能創建一個抽象類」

這是有道理的。 A是抽象的。

我可以使用腳手架從A創建B和其他繼承類嗎?

回答

2

據我所知,你應該添加

using System.ComponentModel.DataAnnotations; 

[Table("TableNameForB")] 
public class B : A 
{ 
    public string Name { get; set; } 
} 

爲屬性爲您具體類

在這裏找到一個完整的例子

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Data.Entity; 
using System.ComponentModel.DataAnnotations; 

namespace ZooLabPoco 
{ 
    public class Context : DbContext 
    { 
     public DbSet<Animal> Animals { get; set; } 
     public DbSet<Zoo> Zoos { get; set; } 
    } 

    public class Zoo 
    { 
     public int Id { get; set; } 
     public virtual ICollection<Animal> Animals { get; set; } 
     public Zoo() 
     { 
      this.Animals = new List<Animal>(); 
     } 
    } 

    public abstract class Animal 
    { 
     public int Id { get; set; } 
     public int ZooId { get; set; } 
     public virtual Zoo Zoo { get; set; } 
    } 

    [Table("Lions")] 
    public class Lions : Animal 
    { 
     public string LionName { get; set; } 
    } 

    [Table("Tigers")] 
    public class Tigers : Animal 
    { 
     public string TigerName { get; set; } 
     public int TailLength { get; set; } 
    } 

    class Program 
    { 
     static void Main(string[] args) 
     { 

      var context = new Context(); 
      context.Database.Delete(); 
      context.Database.CreateIfNotExists(); 


      var zoo = new Zoo(); 
      zoo.Animals.Add(new Lions { LionName = "Fritz" }); 
      zoo.Animals.Add(new Lions { LionName = "Jerry" }); 
      zoo.Animals.Add(new Tigers { TigerName = "Pluto" }); 

      context.Zoos.Add(zoo); 
      context.SaveChanges(); 

     } 
    } 
} 
+0

在這個答案互相沖突的兩個例子。 第一個使用「TableNameForA」(基本表名稱),而第二個使用混凝土表名稱:「獅子」而不是「動物」。哪個是對的? – 2014-03-07 10:22:22

+1

必須提交的名稱是具體的類。感謝您的警告! – 2014-03-10 16:49:23