使用EF Core訪問SqlServer數據庫


如題。其實很簡單,以前調試心不靜,各種不通。

代碼中各種引用,自行添加。

數據庫d1,表t1,xm是key:

 

 

 上下文類:

 1 using Microsoft.EntityFrameworkCore;
 2 
 3 namespace ConsoleApp1
 4 {
 5     public partial class D1 : DbContext
 6     {
 7         protected override void OnConfiguring(DbContextOptionsBuilder options)
 8            => options.UseSqlServer(@"data source=(localdb)\mssqllocaldb;initial catalog=d1;user id=sa;password=xxx");
 9 
10         public virtual DbSet<t1> t1 { get; set; }
11     }
12 }

其中第七行的代碼,在開始執行查詢(主程序中的操作)之前執行。

也就是說,配上第八行的東西,訪問數據庫就差不多一路pass了。

實體類:

using System.ComponentModel.DataAnnotations;
namespace ConsoleApp1
{
    public class t1
    {
        [Key]
        [StringLength(10)]
        public string xm { get; set; }

        public byte? nl { get; set; }
    }
}

很簡單,沒啥說的。

調用也簡單:

using System;
using System.Linq;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            D1 d = new D1();
            var t = from x in d.t1 select(x);
            foreach (var item in t)
            {
                Console.Write(item.xm + "," + item.nl);
                Console.WriteLine();
            }
        }
    }
}

運行結果:

ls,18
zs,20

vs2019

v16.82下

.net 5

調試通過。

總結:微軟封的不錯。入門的小伙伴參考着上面的內容,靜心調試。都用起來吧。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM