2016-10-01 77 views
1

我在我的SQL數據庫中有一個視圖。我想要的只是從該視圖中檢索數據。使用代碼優先從數據庫視圖中檢索數據時出錯

我已經添加了POCO類。

namespace WFPersistence.DataModel 
{ 
    public class Instance 
    { 
     public Guid InstanceId { get; set; } 
     public DateTime? PendingTimer { get; set; } 
     public DateTime? CreationTime { get; set; } 
     public DateTime? LastUpdatedTime { get; set; } 
     public int? ServiceDeploymentId { get; set; } 
     public string SuspensionExceptionName { get; set; } 
     public string SuspensionReason { get; set; } 
     public string ActiveBookmarks { get; set; } 
     public string CurrentMachine { get; set; } 
     public string LastMachine { get; set; } 
     public string ExecutionStatus { get; set; } 
     public bool? IsInitialized { get; set; } 
     public bool? IsSuspended { get; set; } 
     public bool? IsCompleted { get; set; } 
     public byte? EncodingOption { get; set; } 
     public byte[] ReadWritePrimitiveDataProperties { get; set; } 
     public byte[] WriteOnlyPrimitiveDataProperties { get; set; } 
     public byte[] ReadWriteComplexDataProperties { get; set; } 
     public byte[] WriteOnlyComplexDataProperties { get; set; } 
     public string IdentityName { get; set; } 
     public string IdentityPackage { get; set; } 
     public long? Build { get; set; } 
     public long? Major { get; set; } 
     public long? Minor { get; set; } 
     public long? Revision { get; set; } 
    } 

    public class Instances : Collection<Instance> 
    { 
    } 
} 

這就是我試圖用視圖來映射。

public class WFPersistenceStore : DbContext 
{ 
    public WFPersistenceStore() : base("WFPersist") 
    { 
    } 

    public DbSet<Instance> PersistedInstances { get; set; } 

    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<Instance>().ToTable("System.Activities.DurableInstancing.Instances"); 
    } 
} 

這是我如何與視圖連接

using (var PersistStore = new WFPersistenceStore()) 
{ 
    var result = from t in PersistStore.PersistedInstances 
       select t; 
    //// 
    /// 
} 

我收到此錯誤:

An unhandled exception of type 'System.ArgumentException' occurred in RentalHost.exe

Additional information: The database name 'System.Activities.DurableInstancing.Instances' is invalid. Database names must be of the form [.].

+0

你的表名需要採用[schema]。[object_name]的形式 - 嘗試重命名它。 –

+0

我嘗試了這種方式,但它抱怨模型不匹配,需要更新。因爲在這種情況下,它將我的POCO類與實際的表格方案相匹配,而不是與視圖方案匹配。希望你明白我的意思。 – immirza

回答

0

我已經解決我的問題,只是把下面一行在我的上下文類的構造函數中(即WFPersistenceStore)。

Database.SetInitializer<WFPersistenceStore>(null); 

這在官方文檔中沒有提及,如果我沒有錯的話。

上述行僅適用於EF6版本,但不適用於早期版本的EF。

0

你的方法應該是這樣

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
     { 
      modelBuilder.Entity<Instance>().ToTable("Instances"); 
     } 
+0

即使這樣,它也會產生相同的錯誤「自從創建數據庫以來,支持'WFPersistenceStore'上下文的模型已經發生了變化。考慮使用Code First Migrations來更新數據庫(http://go.microsoft.com/fwlink/?LinkId= 238269)。」 – immirza

相關問題