LINQ to SQL - mapping exception when using abstract base classes

前端 未结 5 1049
离开以前
离开以前 2020-12-08 03:20

Problem: I would like to share code between multiple assemblies. This shared code will need to work with LINQ to SQL-mapped classes.

I\'ve encountered the same issu

5条回答
  •  Happy的楠姐
    2020-12-08 03:36

    I've had luck defining data classes in a shared assembly and consuming them in many assemblies versus mapping many assemblies' data classes to a shared contract. Using your example namespaces, put a custom DataContext and your shared data classes in TestLinq2Sql.Shared:

    namespace TestLinq2Sql.Shared
    {
        public class SharedContext : DataContext
        {
            public Table Users;
            public SharedContext (string connectionString) : base(connectionString) { }
        }
    
        [Table(Name = "Users")]
        public class User
        {
            [Column(DbType = "Int NOT NULL IDENTITY", IsPrimaryKey=true, CanBeNull = false)]
            public int Id { get; set; }
    
            [Column(DbType = "nvarchar(40)", CanBeNull = false)]
            public string Name { get; set; }
    
            [Column(DbType = "nvarchar(100)", CanBeNull = false)]
            public string Email { get; set; }
        }
    }
    

    Then consume the DataContext from any other assembly:

    using (TestLinq2Sql.Shared.SharedContext shared = 
        new TestLinq2Sql.Shared.SharedContext(
            ConfigurationManager.ConnectionStrings["myConnString"].ConnectionString))
    {
        var user = shared.Users.FirstOrDefault(u => u.Name == "test");
    }  
    

提交回复
热议问题