2009-05-28 239 views
0

我正在觀看關於[LINQ] [1]的視頻,並且遇到了問題。在這段視頻中,Mike爲數據庫名稱使用了一些自定義屬性,但這對我不起作用。使用自定義屬性

我的代碼(正常工作):

class MyContext : DataContext 
{ 
    public MyContext(string conStr) : base(conStr) 
    { 
    } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     MyContext ctx = new MyContext("server=.;database=AdventureWorks;Integrated Security=SSPI"); 
     Console.WriteLine(ctx.Connection.ConnectionString); 
     ctx.ExecuteCommand("insert into _table (a, b) select {0}, {1}", "5", "B"); 

     Console.WriteLine("That's it!"); 
     Console.ReadLine(); 
    } 
} 

如何,我想它是(在類MyContext之前創建對象CTX和額外的自定義屬性的數據庫名稱的通知丟失的數據庫參數):

[Database(Name="AdventureWorks")] 
class MyContext : DataContext 
{ 
    public MyContext(string conStr) : base(conStr) 
    { 
    } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     MyContext ctx = new MyContext("server=.;Integrated Security=SSPI"); 
     Console.WriteLine(ctx.Connection.ConnectionString); 
     ctx.ExecuteCommand("insert into _table (a, b) select {0}, {1}", "5", "B"); 

     Console.WriteLine("That's it!"); 
     Console.ReadLine(); 
    } 
} 

這會拋出異常「無效的對象名稱_table」,就像我不會定義任何數據庫名稱一樣。我錯過了什麼嗎?這是我第一次使用自定義屬性,...

回答

1

你仍然需要閱讀的屬性。您必須使用反射來解析myContextConstructor中的值。

0

使用設計它在類的靜態成員從VS創建的上下文展望:

private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource(); 

這裏Context類的開頭:

[Database(Name = "Blah")] 
    public partial class TestDataContext : System.Data.Linq.DataContext 
    { 

     private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource(); 

    #region Extensibility Method Definitions 
    partial void OnCreated(); 
    partial void InsertAdmin(Admin instance); 
    partial void UpdateAdmin(Admin instance); 
    partial void DeleteAdmin(Admin instance); 
    partial void InsertUser(User instance); 
    partial void UpdateUser(User instance); 
    partial void DeleteUser(User instance); 
    #endregion 

     public TestDataContext() : 
       base(global::TestStuff.Properties.Settings.Default.FraudAnalystConnectionString, mappingSource) 
     { 
      OnCreated(); 
     } 

     public TestDataContext(string connection) : 
       base(connection, mappingSource) 
     { 
      OnCreated(); 
     } 

     public TestDataContext(System.Data.IDbConnection connection) : 
       base(connection, mappingSource) 
     { 
      OnCreated(); 
     } 

     public TestDataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) : 
       base(connection, mappingSource) 
     { 
      OnCreated(); 
     } 

     public TestDataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) : 
       base(connection, mappingSource) 
     { 
      OnCreated(); 
     } 

這僅僅是構造函數...不是整個類...但是要選擇創建Linq to Sql Classes模板後,只需從服務器資源管理器的表中拖動即可。