Tutorial :Using custom attributes



Question:

I am watching a video about [LINQ][1] and came across a problem. In this video, Mike uses some custom attributes for database name and that does not work for me.

My code (which works fine):

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();      }  }  

How I'd like it to be (notice the missing database parameter in creating of the object ctx and additional custom attribute for database name before the class MyContext):

[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();      }  }  

This throws exception 'invalid object name _table', just like I wouldn't define any database name. Am I missing something? It's my first time using custom attributes,...


Solution:1

You still need to read the attribute. You'll have to use reflection to parse the value in your myContextConstructor.


Solution:2

Looking at the context created from VS using the designer it has a static member in the class:

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

here the the beginning of the Context class:

 [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);      





        
Previous
Next Post »