查看有关如何使用数据库上下文池的示例,我发现它是设计用于ServiceCollection
:
var serviceProvider = new ServiceCollection()
.AddDbContextPool<AdventureWorksContext>(options => { //options })
.BuildServiceProvider();
Run Code Online (Sandbox Code Playgroud)
但是简单注入器呢?是否可以在Simple Injector容器中注册数据库池?
ps我的应用不是ASP.NET MVC,只是DAL
语境
当前,我正在使用.NET Core创建用C#编写的提取,转换和加载(ETL)应用程序。ETL应用程序的目标是通过Entity Framework Core 2.1.0和更高版本2.1.1访问的数据库。由于模式是固定的,因此使用数据库优先方法。Microsoft提供了以下指南来解决这种情况。该指南指出,Scaffold-DbContext
Package Manager控制台中的CLI命令可用于生成DbContext和相应的实体模型。
在此项目的早期,我已经成功使用了此CLI命令。但是,模型的命名并不直接对应于表名和列名。此CLI工具的较新版本提供了一个option -UseDatabaseNames
,因此我选择重新运行此命令以生成一些更新的模型。另外,我计划在将来重新生成DbContext。
问题
不幸的是,运行Scaffold-DbContext
命令现在返回以下错误:Instance failure.
。详细选项使您可以更深入地了解出了什么问题,但是我不清楚到底出了什么问题以及如何解决。
命令
Scaffold-DbContext "[ConnectionString]" Microsoft.EntityFrameworkCore.SqlServer -UseDatabaseNames -OutputDir Models -v -force
Run Code Online (Sandbox Code Playgroud)
详细输出
Using project '[ProjectName]'.
Using startup project '[ProjectName]'.
Build started...
Build succeeded.
C:\Program Files\dotnet\dotnet.exe exec --depsfile C:\Repos\[Client]\[ProjectName]\[ProjectName]\[ProjectName].Service\bin\Debug\netcoreapp2.1\[ProjectName].Service.deps.json --additionalprobingpath C:\Users\[MyComputerUsername]\.nuget\packages --additionalprobingpath "C:\Program Files\dotnet\sdk\NuGetFallbackFolder" --runtimeconfig C:\Repos\[Client]\[ProjectName]\[ProjectName]\[ProjectName].Service\bin\Debug\netcoreapp2.1\[ProjectName].Service.runtimeconfig.json C:\Users\[MyComputerUsername]\.nuget\packages\microsoft.entityframeworkcore.tools\2.1.1\tools\netcoreapp2.0\any\ef.dll dbcontext scaffold Server=[ConnectionString] Microsoft.EntityFrameworkCore.SqlServer --json --output-dir Models --use-database-names --force --verbose --no-color --prefix-output --assembly C:\Repos\[Client]\[ProjectName]\[ProjectName]\[ProjectName].Service\bin\Debug\netcoreapp2.1\[ProjectName].Service.dll --startup-assembly C:\Repos\[Client]\[ProjectName]\[ProjectName]\[ProjectName].Service\bin\Debug\netcoreapp2.1\[ProjectName].Service.dll --project-dir C:\Repos\[Client]\[ProjectName]\[ProjectName]\[ProjectName].Service\ --language C# --working-dir C:\Repos\[Client]\[ProjectName]\[ProjectName] --root-namespace [ProjectName].Service
Using …
Run Code Online (Sandbox Code Playgroud) ef-database-first .net-core entity-framework-core-migrations entity-framework-core-2.1 ef-core-2.1
我研究了这个,总是找到这样的例子:
var blogs = context.Blogs
.FromSql("SELECT * FROM dbo.Blogs")
.ToList();
Run Code Online (Sandbox Code Playgroud)
问题是,我不想在Blogs表上运行我的原始SQL.基本上,我想实现这样的接口:
bool ExecuteNonSafeSql(
string connectionString,
string sql);
Run Code Online (Sandbox Code Playgroud)
有没有办法用DbContext做到这一点?
我想将此 sql 查询转换为 linq :
select * from A a
join B b on ( (a.level1= b.PerimeterID and b.PerimeterLevelID = 1)
OR (a.level2= b.PerimeterID and b.PerimeterLevelID = 2)
OR (a.level3= b.PerimeterID and b.PerimeterLevelID = 3)
)
Run Code Online (Sandbox Code Playgroud)
我试过的:
from a in A
join b in B on new {PerimeterID = a.level1, PerimeterLevelID = 1 } equals new { b.PerimeterID, b.PerimeterLevelID }
where (a.level2 == b.PerimeterID && b.PerimeterLevelID == 2) ||
(a.level3 == b.PerimeterID && b.PerimeterLevelID == 3)
Run Code Online (Sandbox Code Playgroud)
它生成这个 sql 查询:
select …
Run Code Online (Sandbox Code Playgroud) 我的数据库中有一个名为“dbo.Viewtest”的 SQL 视图。此视图组合了其他 2 个具有相同列类型的表的数据。该视图还添加了一列以显示数据源自哪个表。
这是 SQL Server 对象资源管理器中 SQL 视图的样子:
身份证 | 类型 | 内容 | 地点
1 | H1 | 欢迎!| 家
2 | p | 登录 | 家
3 | h2 | 指南 | 家
1 | H1 | 信息 | 活动
2 | p | 关注 | 活动
该视图由 2 个表创建,其中一个称为“HomeContent”,另一个称为“EventsContent”(因此是位置列)。使用以下代码创建了视图:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("CREATE VIEW ViewTest AS " +
"SELECT Id, Type, Content, 'Home' location FROM HomeContent UNION ALL " + …
Run Code Online (Sandbox Code Playgroud) 我已经设置了一个包含 .net core 类库项目和 asp.net core Web api 项目的解决方案。为了使用我的类库,我通过ConfigureServices 添加了接口,其中DataRepo 是类库中的一个类。
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IDataRepo, DataRepo>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
Run Code Online (Sandbox Code Playgroud)
该类库需要获取 API 项目文件 appsettings.json 中特定于环境的连接字符串。我如何将配置设置传递给它?另外,我想在库项目中添加 EF 核心数据模型,并且不想向 API 项目注册 DbContext,而是在库的构造函数中使用连接信息与 DbContext 中的配置一起传递。首先,如何将 appsettings.json 中的配置设置获取到我的类库?
namespace DataLib
{
public class DataRepo : IDataRepo
{
public DataRepo()
{
}
public string GetHello()
{
return "hello from lib";
}
}
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试在我的项目中使用Ef Core。
就我不是在WebApi.csproj现场使用EfCore而言,结构有所不同。实际上,我有一个不同的dll。和一个DependenciesResolver.dll处理我所有的依赖项注入。
在我的EfCore.dll中,我已经安装了两个
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.SqlServer
现在,当我尝试运行命令时(我正在运行的dll是EfCore.dll)
Add-Migration Name
Run Code Online (Sandbox Code Playgroud)
我得到这个:
在类“ Program”上访问IWebHost时发生错误。没有应用程序服务提供商就继续进行。错误:对象引用未设置为对象的实例。无法创建“ StoreContext”类型的对象。将“ IDesignTimeDbContextFactory”的实现添加到项目中,或在设计时查看 https://go.microsoft.com/fwlink/?linkid=851728,以获取其他支持的模式。
sln的结构是这样的
WebApi | EfCore.dll | DependencyResolver.dll,我想保持这种方式,不想允许在我的WebApi中使用EfCore。
解决此问题的方法是什么?
如果在EfCore.dll中有帮助,我可以这样做。
public sealed partial class StoreContext : DbContext, IStoreContext
{
private string _connectionString;
public StoreContext(string connectionString) : base()
{
_connectionString = connectionString;
Database.EnsureCreated();
}
/// db.tbls
public DbSet<Order> Orders { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.AddOrderConfiguration();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(_connectionString);
}
}
Run Code Online (Sandbox Code Playgroud)
像这样被DependencyResolver调用
private DependenciesResolver RegisterInfrastructure()
{
_serviceCollection.AddScoped<StoreContext>(factory => …
Run Code Online (Sandbox Code Playgroud) c# entity-framework-core .net-core asp.net-core-2.0 ef-core-2.1
当我在某些中间件中运行以下代码时
var apiKeys = _appContext.apikey.ToList();
Run Code Online (Sandbox Code Playgroud)
我得到这个错误
System.InvalidOperationException:类型'System.Int16'和'System.Boolean'之间没有定义强制运算符。
这是我的ApiKey类
public class ApiKey
{
public string apikeyid { get; set; }
public string uid { get; set; }
public string apikey { get; set; }
public bool isactive { get; set;}
public bool ispaid { get; set; }
public bool ismod { get; set; }
public bool isadmin { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我曾与Postgresql db一起工作过,然后才移到MySQL。这与从tinyint(在数据库中)到bool(在类中)有关吗?
我正在使用 MySql.Data.EntityFrameworkCore 8.0.13
我一直在使用表达式树的 EF Core 查询的动态过滤器类中工作,一切看起来都很好,过滤器正在工作,我可以传递一个过滤器集合并且它可以工作,但是当我查看 SQL 语句时,它正在查询整个表并对结果集合应用过滤器,这是我的课程......
public static class QueryExpressionBuilder
{
private static readonly MethodInfo ContainsMethod = typeof(string).GetMethod("Contains", new[] { typeof(string) });
private static readonly MethodInfo StartsWithMethod = typeof(string).GetMethod("StartsWith", new[] { typeof(string) });
private static readonly MethodInfo EndsWithMethod = typeof(string).GetMethod("EndsWith", new[] { typeof(string) });
#region DynamicWhere
/// <summary>Where expression generator.</summary>
/// <typeparam name="T"></typeparam>
/// <param name="filters">The filters.</param>
/// <returns></returns>
public static Expression<Func<T, bool>> GetExpression<T>(IList<Filter> filters)
{
if (filters.Count == 0)
return null;
ParameterExpression param = Expression.Parameter(typeof(T), "t");
Expression exp = …
Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个程序包,该程序包将使用JSON文件中的数据来帮助种子数据库,这些数据可以手动创建,也可以从旧数据库中提取.目前,我已经创建了一个泛型类SeedCreator<T>
,它从给定文件中检索JSON(实体的名称加上.json
)并将其反序列化为给定类型的对象.这部分工作正常.
为了使这个过程尽可能动态,我通过使用命名空间标识所有类来对项目中的实体进行反射Entities
.有了这个,我循环检索List
并检查JSON文件是否存在.如果是的话,我将路径和泛型类型传递给类SeedsCreator
.在运行时进行调试时Add-Migration
,数据会按照我对JSON文件的预期返回,但在modelBuilder
返回变量后我得到错误The seed entity for entity type 'Table1' cannot be added because there was no value provided for the required property 'Id'.
如果我手动输入以下它可以正常工作.
modelBuilder.Entity(typeof(Table1)).HasData(data);
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激.特别是如果我是盲人并做了一些非常简单和愚蠢的事情.
public class Seeds
{
public ModelBuilder CreateSeeds(ModelBuilder modelBuilder)
{
var entities = (from t in Assembly.GetExecutingAssembly().GetTypes()
where t.Namespace != null && (t.IsClass && t.Namespace.Contains("Entities"))
select t).ToList();
foreach (var type in entities)
{
if (File.Exists("./Seeds/" + type.Name + ".json"))
{
Type[] …
Run Code Online (Sandbox Code Playgroud) c# entity-framework-core .net-core asp.net-core-2.1 ef-core-2.1
让我们假设这种情况
实体
public virtual List<Address> AddressHistory { get; set; }
public Address Address
{
get
{
if (AddressHistory.Any())
{
return AddressHistory.OrderByDescending(x => x.CreationDate).FirstOrDefault();
}
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
根据条件请求地址时,如下所示:
dbContext.MyEntity.Where(e => e.Address.Street == "some stuff");
Run Code Online (Sandbox Code Playgroud)
我得到一个空引用异常。
为什么呢 有办法使它起作用吗?
编辑:对于那些认为地址可能为空的人,在这样做的时候可以使用:
dbContext.MyEntity.Where(e => e.AddressHistory.OrderByDescending(x => x.CreationDate).FirstOrDefault().Street == "some stuff");
Run Code Online (Sandbox Code Playgroud)
编辑:对于将其标记为重复的人,我认为您在这里不明白这个问题。请删除标记。
因此,总结一下:
如果我使用getter => null异常,因为子级(AdressHistory)不会被延迟加载。如果我直接在efcore表达式中的getter中使用代码,则它可以工作。
这意味着使用吸气剂在EFCore中不起作用。
我有实体类,如下所示:
public class Bike
{
public int Id { get; set; }
public int ModelId { get; set; }
public Model Model { get; set; }
public Contact Contact { get; set; }
}
[Owned]
public class Contact
{
[Required]
[StringLength(255)]
public string Name { get; set; }
[StringLength(255)]
public string Email { get; set; }
[Required]
[StringLength(255)]
public string Phone { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
它将默认生成表:
migrationBuilder.CreateTable(
name: "Bike",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", …
Run Code Online (Sandbox Code Playgroud) 我有一个非常简单的获取,它从字面上抓取整个数据库集并通过线路返回它.有问题的集合目前约为28,000行.
在本地测试时,对数据库的调用在不到一秒的时间内完成,但是大摇大摆的调用大约需要一分钟.在我们的生产环境中,完成调用大约需要1-2分钟(我们没有准确的数据库调用的时间码,但我们在前端计时需要多长时间,而且它也是1-2分钟).
数据调用和它到达前端之间的某些东西需要很长时间,而且我不确定如何解决它.
代码字面意思是:
[HttpGet]
public IActionResult GetAllCustomers()
{
return Ok(_context.Customers);
}
Run Code Online (Sandbox Code Playgroud)
我还能做些什么来调试这个?
我们的工作解决方案将是显着限制数据集,而不是返回<1000条记录,但业务首选项是拥有所有内容并让前端表对其进行排序和过滤.
在云雀上,我从模型中删除了所有相关对象,并将其剥离到表格中的10个左右列,但仍然需要很长时间.
ef-core-2.1 ×13
c# ×10
.net-core ×4
asp.net-core ×3
linq ×2
sql-server ×2
c#-6.0 ×1
dbcontext ×1
entity-framework-core-migrations ×1
lazy-loading ×1
mysql ×1
sql ×1
sql-view ×1