23,540 questions
0
votes
1
answer
34
views
Entity Framework Core: how to get the list of attribute codes for each item?
I am writing a Web API endpoint, data comes from SQL Server, and I'm using EF Core 8.0.
I have a table of products and another table that maps the product codes to product attributes (one-to-many) ...
1
vote
0
answers
67
views
How to async fill the navigation property used for filtering when paging?
Learning EF Core, I am changing my mind on how to get the list of products with additional information (here symbolic code) -- see the loosely related (abandoned approach) at How to conditionally ...
1
vote
1
answer
105
views
'SQLite Error 19: 'FOREIGN KEY constraint failed'.' while try to insert data
I am trying to run my database code, but I keep getting this error and I've done whatever I can think of to fix it, whether it is random posts, or chatgpt, but I can't seem to figure it out. The ...
Best practices
0
votes
4
replies
69
views
Should I create navigation properties for BaseEntity's CreatedBy/ModifiedBy fields in Entity Framework Core?
I'm building an e-commerce application with ASP.NET Core Web API using Entity Framework Core and ASP.NET Core Identity. I have a BaseEntity class that tracks audit information (who created and last ...
-4
votes
2
answers
201
views
Why does this code return a null reference exception without warning?
My understanding of C#'s null safety features (from C# 8.0 onwards) is that (possibly) null variables must be typed as nullable and that the compiler will statically detect any parts of the code which ...
Best practices
0
votes
2
replies
67
views
Filling the `entityIds` property in EF Core
I am currently developing a module for an ASP.NET Core Web API that uses EF Core to talk to MySQL. The problem is I have no idea how to make EF Core fill the entityId property.
Here is the example ...
1
vote
1
answer
92
views
How to conditionally compose the EF from parts?
I have two tables Products and CustomerProduct. I need to compose an Entity Framework Core object that returns the result based on arguments of the Web API endpoint method.
The method roughly works ...
0
votes
1
answer
107
views
EF Core 9 migration fails on production database copy with "Cannot release the application lock" error
I'm using EF Core 9 and I'm trying to run a migration against a copy of our production database.
On our local development databases everything works, but on the production copy the migration fails ...
0
votes
1
answer
101
views
How to have a repository-type table without FKs?
Is it possible to have a type in Entity Framework Core that doesn't create FKs to every other table that uses it? Creating the DB-Scheme from the C#-model with Add-Migration and Update-Database.
For ...
1
vote
0
answers
53
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
82
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 ...
0
votes
1
answer
100
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
94
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....
1
vote
1
answer
103
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....
17
votes
4
answers
5k
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:
...
-2
votes
0
answers
54
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
113
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
105
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 ...
2
votes
1
answer
184
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
85
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
111
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
89
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
121
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
66
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
102
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
126
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
122
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
128
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
184
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
123
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 ...
4
votes
1
answer
374
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
58
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
210
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
56
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
82
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
253
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
57
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
244
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
239
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
100
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
89
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
374
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
43
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
564
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
274
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 ...