23,536 questions
1
vote
0
answers
37
views
EF Core + Npgsql: "column 'status' is of type application_status but expression is of type text"
I've been struggling for two days with a PostgreSQL enum type issue in Entity Framework Core. Despite all my configuration, EF Core keeps trying to send a string (`text`) to an enum column.
The ...
0
votes
2
answers
72
views
Defining many-to-many with join table foreign key names without concrete c# domain table (shadow join)
I am trying to link a many-to-many relationship without any intermediary class in my domain.
The link is SoundProfiles <-> Switches. They're both not required. The error I get is
One or more ...
Best practices
0
votes
0
replies
39
views
Web API & EF Core: how to conditionally compose the EF from parts? Problem also with the result model
I have two SQL tables Products and CustomerProduct. I need to compose the Entity Framework Core object that returns the result based on arguments of the Web API end-point method.
The method roughly ...
0
votes
1
answer
87
views
Entity Framework Core queries in an ASP.NET Core application targeting an Azure SQL database are running with wildly different runtimes
I have a web app using code-first EF Core.
One of the controllers needs to run what should be a simple query (basically SELECT TOP 1 * FROM companies WHERE id = @id; in EF terms,
var data = await ...
1
vote
1
answer
80
views
Unable to create a 'DbContext' of type 'AppDbContext'. The exception 'Object reference not set to an instance of an object.' was thrown
I'm getting this error :
Unable to create a 'DbContext' of type 'AppDbContext'. The exception 'Object reference not set to an instance of an object.' was thrown while attempting to create an instance....
0
votes
1
answer
76
views
How to use expression setters in ExecuteUpdate again in EF Core 10
Microsoft have changed ExecuteUpdateAsync to accept non-expression setters parameter in NET 10. Now it works this way:
await context.Blogs.ExecuteUpdateAsync(s =>
{
s.SetProperty(b => b....
8
votes
4
answers
2k
views
installing dotnet-ef dotnet tool throws error
I’m trying to install the Entity Framework Core CLI tools globally using the .NET CLI command:
dotnet tool install --global dotnet-ef
However, the installation fails with the following error message:
...
0
votes
1
answer
124
views
EF Core creating multiple objects when the collection contains both NULL and non-NULL values [closed]
I'm experiencing unexpected behaviour with EF Core 6 where a query creates two separate entity instances instead of one when a related collection contains both NULL and non-NULL values.
Code sample:
...
-1
votes
0
answers
47
views
Respect ConcurrencyToken or ConcurrencyCheck on included Properties in EF Core [duplicate]
Given a class A, and a class B, where class A holds a reference to class B, and where some logic in A depends on some state in B, how can i configure EF Core to make sure B has not changed when ...
Advice
2
votes
3
replies
104
views
Does the EF Core 8.0.20 process correctly AsSplitQuery queries with conditions & paging that pull data from tables with one-to-many relationships?
Do you know if EF Core correctly processes queries that apply filters and paging and select data from tables with one-to-many relationships when .AsSplitQuery() is used?
If you go here: https://learn....
Advice
0
votes
5
replies
101
views
C# & EF Core nullable type return vs not found or multiple database rows
I have the following use case: the database contains a row with a nullable column, and I would like to request only that column value from the database for a single row.
This can easily be done using ...
1
vote
1
answer
144
views
.NET migrations with vulnerabilities
I am attempting to create a new EF Core migration using the add-migration command in the Visual Studio Package Manager, but the command is failing with the following error:
The running command ...
2
votes
1
answer
68
views
How can I solve an EF Core error querying SQLite?
I just got my .Net 9 Maui app working with EF Core and SQLite. I have one row of data in the database that looks like this:
I have a simple query that runs when the app loads. The repository method ...
3
votes
1
answer
107
views
Self-contained publish works locally but fails on other machines: "Failed to update database to latest state"
I'm creating a self-contained publish of my ASP.NET Core application.
When I run it on my development machine, everything works correctly: the app can connect to the remote SQL Server and db.Database....
0
votes
2
answers
71
views
How do I resolve a error global::System.Diagnostics.Debugger.Break(); in a .Net Maui application
I'm trying to configure a new Maui app to use EF and Sqlite following this guide: https://learn.microsoft.com/en-us/dotnet/maui/data-cloud/database-sqlite?view=net-maui-9.0
For a long time I got an ...
3
votes
3
answers
118
views
Delete rows in two tables with relations in both directions using Entity Framework Core
How do you delete rows in tables using Entity Framework (Core), when you have two tables that are referencing each other in both directions?
Consider there classes:
public class ImageSeries
{
int ...
1
vote
1
answer
60
views
EF Core - Custom DBFunction - Usage with Linq Dynamic
I have a simple DbFunction to convert a date string column (mm-dd-yyyy) to datetime before ordering. The DbFunction is set up in the DatabaseContext class as follows.
[DbFunction("...
2
votes
0
answers
95
views
NUMBER(1,0) mapped to bool instead of int causes conversion and mapping errors
I'm connecting to an Oracle database using EF Core.
When scaffolding the database (Scaffold-DbContext), EF Core automatically maps columns of type NUMBER(1,0) to bool.
To avoid this, I changed the ...
3
votes
2
answers
115
views
How to handle EF Core update + Azure Blob upload transactionally in a single request?
I'm building an ASP.NET Core Web API where I need to upload a file to Azure Blob Storage and update an EF Core entity in a single request.
The challenge is that EF Core supports transactions, but ...
1
vote
2
answers
117
views
Foreign keys are null when retrieved, even though stored correctly in database
I have the following classes in my (code-first) Entity Framework Core database schema:
public class User
{
public int Id { get; set; }
// ... Irrelevant bits omitted
}
public class Church
{
...
2
votes
1
answer
118
views
.NET / EF Core / AutoMapper causing PostgreSQL "invalid input syntax for type json" error when saving entity
I'm working on a .NET 8 project using Microsoft.EntityFrameworkCore 8.0.7 with PostgreSQL as the database. I have a table that contains a jsonb column, and I'm using AutoMapper to map a DTO to the ...
1
vote
1
answer
166
views
Repository Interface to perform database bulk update with Entity Framework Core 8.0.6
I have the following interface signature that I want to use for a more efficient bulk update using EF Core 8.0.6
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Query;
using ...
7
votes
1
answer
205
views
Multiple SUM issue with EF SQL
I'm trying to use Linq to generate a SQL command like this
return await query.GroupBy(x => new
{
Id = x.xId,
...
3
votes
2
answers
116
views
Error when accessing data, EF Core seems to create its own column
I have a project that has uses a database-first approach. I have used db-scaffold to create the models and have also created 'custom' models to contain extra info and code.
I have a model class ...
3
votes
1
answer
258
views
An exception was thrown while attempting to evaluate the LINQ query parameter expression
Have a rather simple LINQ query:
var objectExternalIds = new string[] { "abc" };
var query = from order in Context.Order
join apointment in Context.Appointment on order.Nr equals ...
1
vote
1
answer
113
views
Entity with compound primary key also create index on single column [duplicate]
I just added an EF entity called PurchaseOrderProduct, which creates a many-to-many link between my PurchaseOrders and Products.
[PrimaryKey(nameof(PurchaseOrderId), nameof(ProductId))]
public class ...
0
votes
0
answers
54
views
Custom primitive type collection in EF Core (8)
I have a nested entity, defined like this:
entity.OwnsOne(e => e.EncryptedElements, o =>
{
o.ToJson();
o.OwnsMany(x => x.Values, o =>
{
o.Property(x ...
6
votes
3
answers
207
views
Preserve a foreign key using a uniqueness constraint while dropping a primary constraint
I have a SQL Server database I mostly interact with using EF Core in a .NET project: I'll analogize my domain logic for simplicity.
I have a Fruits table holding general fruit data in columns Weight, ...
2
votes
1
answer
55
views
EF Core Attach method not updating related entities
The entities are:
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
public IList<Employee> Employees { get; } = new List<Employee>();
}
...
0
votes
2
answers
75
views
ASP.NET Core Web API + EF: how to convert the list of entities to queryable?
I need to rewrite the code for getting and filtering the list of products. The older version used directly the SQL table Products, and filtered the result by code or name of a product, category, etc, ...
3
votes
1
answer
246
views
How can I project an entity in such a way that it remains filterable on the database?
I am trying to project the result of the following query into EF Core 8 entities:
select foo.*
, (case when hst.Id is not null and foo.OtherColumn = 1 then 42 else null end)
as Bar
...
2
votes
1
answer
52
views
EF Core HasOne(...).WithOne() throws many InvalidException at migration
I am facing this problem at migration - here are my model classes:
// Principal (parent)
public class Blog
{
public int Id { get; set; }
}
// Dependent (child)
public class BlogHeader
{
...
1
vote
2
answers
237
views
Why let with where clause can't translate to SQL?
I have a code snippet that uses let with a where clause.
private List<string> Example2()
{
var query1 =
from c in _context.Customers
let custPurchases = _context.Purchases....
1
vote
0
answers
215
views
Unable to create a 'DbContext' of type 'RuntimeType'
I get this error when migrating from Entity Framework:
dotnet ef migrations add initApp
Unable to create a 'DbContext' of type 'RuntimeType'. The exception 'Unable to resolve service for type '...
0
votes
1
answer
92
views
Receiving FOREIGN KEY constraint error when trying to update database in the EF Core [duplicate]
I have the following entities
Film:
using System.ComponentModel.DataAnnotations.Schema;
namespace MyWebAPIApplication.Entities
{
public class Film : Base
{
string Title { get; set; }
...
1
vote
1
answer
97
views
How to configure model with two principals related to the same child? [closed]
I've got a class model with two principal classes (PrincipalEntity1, PrincipalEntity2) which are both related to the same child entity (TwiceDependentEntity). PrincipalEntity2 is related directly to ...
1
vote
0
answers
87
views
How to access DbSet properties at runtime [duplicate]
I am very new to development with ORMs.
In my project, where I use Entity Framework Core, I want to create a class that would encapsulate whole interaction with database, i.e. through which I would ...
0
votes
0
answers
123
views
How can I use Entity Framework Core's direct update with a property that has converter
When setting the value on the entity, it works as easily as assigning an empty collection to the property. The property has converters to-from JSON.
However, both throw exceptions:
await db....
2
votes
1
answer
361
views
How can I automatically apply custom naming conventions for PK, FK, index, sequence and default column values in EF Core migrations?
I am using Entity Framework Core and I want to enforce custom naming conventions automatically for PKs, FKs, indexes, and sequences during migrations.
My naming rules are as follows:
Primary key (PK):...
0
votes
0
answers
38
views
EF Core 9 Scaffolding NPGSQL - attribute tags vs modelBuilder
When I ran a scaffold command on my NPGSQL db with the typical default format I find on the web:
Scaffold-DbContext <connection-string> OutputDir Models -Force
It created all my model classes ...
1
vote
1
answer
429
views
How to correctly configure the MapperConfiguration?
private readonly IMapper _mapper;
public CreateDepartmentRequestHandlerTests()
{
var config = new MapperConfiguration(cfg => cfg.AddProfile(new CreateDepartmentProfile()));
_mapper = ...
3
votes
1
answer
251
views
Safely rename table in EF Core
I'd like to rename a table in Entity Framework Core, code first. I do not want to drop and create the table, as this would lose all my data. As I search for information on this, I see that the vast ...
1
vote
0
answers
67
views
Microsoft.EntityFrameworkCore.Sqlite TOP and LIMIT SQL syntax error
In Entity Framework Core 9.0.9, the query builder fails with SQLite Syntax
builder.Services.AddDbContext<MyDbContext>(fun options ->
options.UseSqlite(connectionString) |> ignore
It ...
1
vote
0
answers
53
views
ASP.NET Core background/singleton service — how should I access DbContext safely? [duplicate]
I have an ASP.NET Core 8 app with a long-lived service that refreshes an in-memory cache on a timer. I registered the service as a singleton (it’s a hosted background worker), and it needs to query ...
1
vote
2
answers
138
views
Reverse a LINQ to Entities query?
How do I use Reverse to reverse the order of the results of a LINQ to Entities query?
Something like:
var result = dbContext.Users.Where(a => a.Name != null).Reverse();
0
votes
1
answer
101
views
.NET Equals override not being called inside FirstOrDefaultAsync
I'm in a .NET 6 web application with EFCore, and I have these boilerplate abstract classes and interfaces for defining entities. I know it's quite a number of complexity layers, but it really helps me ...
0
votes
0
answers
88
views
How to add rows to a relationship phantom table in EF core [duplicate]
I want to create a custom admin user from the DbContext, so that when my microservices are started in Docker Compose, an admin user is automatically set up by default when migrations are applied to ...
0
votes
1
answer
96
views
How can I use existing PascalCase entity classes with EF Core scaffolded context that expects lowercase class names?
I'm migrating a .NET Framework project using EF 6 to EF Core with .NET Standard 2.0. My original EF 6 setup created lowercase, plural table names in the database, but I have manually-created entity ...
2
votes
2
answers
159
views
Entity Framework Core is using literal values instead of parameters. Do I need to worry for SQL injection
I have an extension for Entity Framework Core query to support between and I see that the SQL being parsed includes literal values. Is it vulnerable for SQL injection attacks?
This is the extension ...
0
votes
1
answer
91
views
How to resolve EF Core continuous migration error with npgsql HiLo?
I'm using Hilo with a custom sequence name. When creating migrations, EF Core always creates a migration to drop the sequence with the normal name. Since EF Core 9.0, this produces a runtime exception ...