C#使用EF訪問sqlserver數據庫


一、首先運行命令安裝NuGet包:(使用命令行可以避免一些NuGet包版本兼容問題)

1、Install-Package Microsoft.EntityFrameworkCore

2、Install-Package Microsoft.EntityFrameworkCore.SqlServer

二、創建一個實體類Z_Result_log

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp4.Model
{
  public class Z_Result_log
  {
    [Key]
    public int id { get; set; }

    public string entryid { get; set; }

    public string content { get; set; }
    public DateTime createtime { get; set; }

  }
}

三、創建SqlDatabase類

 

using ConsoleApp4.Extensions;
using ConsoleApp4.Model;
using Microsoft.EntityFrameworkCore;

namespace ConsoleApp4
{
  public partial class SqlDatabase : DbContext
  {
    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
      options.UseSqlServer("data source=數據庫地址;initial catalog=數據庫名稱;user id=登錄名;password=密碼");
    }
    public virtual DbSet<Z_Result_log> Logger { get; set; }//數據庫中的表名
  }
}

四、訪問數據庫

SqlDatabase db = new SqlDatabase();
var loglist = db.Z_Result_log.ToList();

 


免責聲明!

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



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