最近需要连接外部的SqlServer 查询了一些答案发现有很多一样但就是连不上,分享一个我能连上方法
通过Json读取连接信息
"ConnectionStrings": {
"DbConnectionString": "Data Source=.;Database=SqlDB;User ID=SqlDB2022;Pwd=SqlDB2022;MultipleActiveResultSets=True"
}
private IConfigurationRoot _configurationRoot;
var connectStrings= _configurationRoot.GetConnectionString("DbConnectionString");
DBContext的设置
这里有一点要提醒 EFCore6.0之后通过视图查询数据没有DBQuery.ToView了,直接可以DBSet.ToView查询视图,如果是表就ToTable
internal class ACCOUNTSDbContext : DbContext
{
public vwAP_ACCOUNTSDbContext(DbContextOptions<vwAP_ACCOUNTSDbContext> options)
: base(options)
{
}
public vwAP_ACCOUNTSDbContext()
{
}
public DbSet<ACCOUNTS> ACCOUNTS { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(connectStrings);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ACCOUNTS>().ToView("ACCOUNTS");
}
}
此时我们可以测试是否可以查出数据了
查询视图我们会有一个问题就是可能查出的多条数据都是重复的,这里我们要禁用EFCore的跟踪缓存 在后面加上AsNoTracking(),这样子我们就可以查多不同的信息了
public static List<ACCOUNTS> GetACCOUNTSDbContextBySQLServer(this string Account_NUMBER)
{
ServiceCollection _GlobalServiceCollection = MainWindow.GlobalServiceCollection;//这里不用管 是我的全局Server
var sp = _GlobalServiceCollection.BuildServiceProvider();
List<ACCOUNTS>? fields;
using (ACCOUNTSDbContext? db = sp.GetService<ACCOUNTSDbContext>())
{
fields = db.ACCOUNTS.AsNoTracking().Where<ACCOUNTS>(c => c.ACCOUNT_NUMBER == Account_NUMBER).ToList();
}
return fields ?? null;
}