首页 > 数据库技术 > 详细

使用EF Core访问SqlServer数据库

时间:2020-12-08 09:37:27      阅读:83      评论:0      收藏:0      [点我收藏+]

如题。其实很简单,以前调试心不静,各种不通。

代码中各种引用,自行添加。

数据库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

调试通过。

总结:微软封的不错。入门的小伙伴参考着上面的内容,静心调试。都用起来吧。

 

使用EF Core访问SqlServer数据库

原文:https://www.cnblogs.com/wanjinliu/p/14100261.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!