Search code examples
c#linq-to-sql.net-5

LINQ to SQL not supported in .net 5.0?


My project used .NetFramework 4.6.2 with "LINQ to SQL" query from MSSQL. A class define all tables which are needed query in database and inheritance to DataContext(System.Data.Linq).

Recently, I am going to upgrade the program to .net5.0. However, I discover "LINQ to SQL" seems like doesn't support to .net5.0.

Could anyone advise how to write "LINQ to SQL" in .net5.0 or using other ways please?

Thanks.

--

Apr 23 PM6:38 Update: I just found SqlSugarCore on Nuget, and test it is okay to use. But still wondering is there any similar tools could use?


Solution

  • I have tried to use EFCore and it's work.

    Just install Microsoft.EntityFrameworkCore and Microsoft.EntityFrameworkCore.SqlServer in NuGet.

    Replace those showed errors from L2S to EFCore. Example: DataContext(L2S) => DbContext(EFCOre), public Table TableA;(L2S) => public DbSet TableA { get; set; }(EFCore)...etc

    Be careful of that if your table have more than one primary key, then you have to write override OnModelCreating as belowed, TableAClass has three keys, and TableBClass has one key.

    。Setup key of per table

    protected override void OnModelCreating(ModelBuilder _modelBuilder)
            {
                _modelBuilder.Entity<TableAClass>().HasKey(_obj => new { _obj.Key1, _obj.Key2, _obj.Key3 });
                _modelBuilder.Entity<TableBClass>().HasKey(_obj => new { _obj.Key1 });
            }
    

    I have got stuck few days, and couldn't find an example on internet. Thus, I decided to put my code here.

    。Setup Database Class

    public class DBClassName : DbContext
        {
            public DbSet<TableAClass> TableAs { get; set; }
            public DbSet<TableBClass> TableBs { get; set; }
    
            protected override void OnModelCreating(ModelBuilder _modelBuilder)
            {
                _modelBuilder.Entity<TableAClass>().HasKey(_obj => new { _obj.Key1, _obj.Key2, _obj.Key3 });
                _modelBuilder.Entity<TableBClass>().HasKey(_obj => new { _obj.Key1 });
            }
    
            public DBClassName(string _connStr) : base(GetOptions(_connStr))
            {
            }
    
            private static DbContextOptions GetOptions(string connectionString)
            {
                return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder<DBClassName>(), connectionString).Options;
            }
    
    
        }
    

    。Setup Table Class

    [Table("TableName")]
        public class TableClassName
        {
            public string ColumnA { get; set;}
    
            public string ColumnB { get; set;}
    
        }
    

    This answer should credits to all who helping me in comments.