Click here to Skip to main content
15,885,869 members
Everything / EF Core

EF Core

EF-Core

Great Reads

by DaveDavidson
In this article, I show LINQ to Entities syntax that will produce queries with CROSS APPLY and LEFT OUTER JOIN clauses.
by Ken Haggerty
Scaffold and modify Identity in the new ASP.NET Core 2.2 Razor pages template
by Coding Notes
An introduction to ASP.NET Core MVC

Latest Articles

by Mark Pelf
Overview of new changes to EF8 – support for Row SQL returning Non-entities.
by David_Cui
To introduce a free library to save some tedious work for writing mapping code between entities and DTOs
by towaso
A short example on how to create a hierarchical web checklist
by DiponRoy
How to delete all rows in EF Core 6 using alternate options

All Articles

Sort by Score

EF Core 

12 May 2017 by DaveDavidson
In this article, I show LINQ to Entities syntax that will produce queries with CROSS APPLY and LEFT OUTER JOIN clauses.
22 Dec 2018 by Ken Haggerty
Scaffold and modify Identity in the new ASP.NET Core 2.2 Razor pages template
9 Mar 2022 by Coding Notes
An introduction to ASP.NET Core MVC
31 Jan 2018 by Pawel idzikowski
How to replace the web API request query string to provide case insensitive OData search
25 Dec 2021 by scott_liu
Entity Framework Core client evaluation was disabled by default since version 3.0 because of performance.
5 Apr 2022 by Coding Notes
An introduction to ASP.NET Core MVC
22 Jun 2017 by Kurt Swendson
How to make the migrations to change data type
22 Dec 2018 by Ken Haggerty
Scaffold and modify Identity in the new ASP.NET Core 2.2 Razor pages template
11 Feb 2020 by Richard Deeming
Currently, EF doesn't allow you to modify the primary key of an entity, so cascading updates don't make much sense. You will have to manually edit your migration to enable them, as described in this SO post[^]. There's a suggestion that this...
5 Sep 2021 by Richard Deeming
One of our applications uses EF Core with a single DbContext containing 116 tables, and it doesn't take anywhere near that long to save the changes, even with a full audit log of all changes running every time. It's hard to say what the problem...
18 Sep 2022 by towaso
A short example on how to create a hierarchical web checklist
28 Jun 2023 by Graeme_Grant
I am not sure what your relation database table hierarchical setup is, so I will focus on a typical setup. The data is stored in a flat structure, usually with a pointer to a parent node. So something like this: class Data { public int Id {...
1 Apr 2024 by Mark Pelf
Overview of new changes to EF8 – support for Row SQL returning Non-entities.
8 Mar 2017 by Dave Kreskowiak
Yeah, don't use Entity Framework. The problem with using it is that your DbContext is directly tied to the exact version of the database the context was written against. If the database schema changes, the DbContext has to change with it. This prevents you from using the same DbContext against...
1 Apr 2017 by Stein The Ruler
I must have missed the part about loading entities. I added a GetItemType method to my DbContext which loads the relational data public async Task GetItemType(ItemType.ListTypes type) { ItemType result = await this.ItemTypes.Include(i =>...
31 Jul 2018 by Mike V Baker
1) This isn't going to be specific to your situation because you're not posting any code so I can't see into your data model. But if you're using EF then you don't have to worry about the primary key foreign key values because that's entity framework's job. Your DBContext will have a data...
16 Feb 2019 by Dave Kreskowiak
That is the "warm up time" for EF. It's doing a first connection to the database and verifying that the structure matches what it expects in order to work with your context. There is nothing you can do to "fix" that.
16 Feb 2019 by Gerry Schmitz
You run a scheduler that every morning fires off the "first query of the day" while everyone else is sleeping.
14 Jul 2020 by #realJSOP
Create a stored proc and call it from EF to populate the colle ction. Let the query in the stored proc add the necessary "relationship" columns and populate them. At that point, your child objects should have a reference to the parent. Let the...
16 Jul 2020 by Richard Deeming
EF Core's GroupBy support can be a bit flaky. Try starting the query with the users instead: var skipperLocations = _appContext.Users .Select(u => u.Locations .Where(l => l.Timestamp > cutOffDate) .OrderByDescending(l =>...
14 Nov 2020 by Gerry Schmitz
If you need a "string" to act like a "list", just add another Getter; EF / LINQ doesn't care. public string Categories {get;set;} = "1;2;3"; public ICollection CatList {get{return this.Categories.Split(';').ToList();}}
2 Jun 2021 by Richard Deeming
If you don't want to return any results, don't use FromSqlRaw on a DbSet; use the ExecuteSql* extension methods on the Database façade. int returnValue = context.Database.ExecuteSqlRaw("EXEC procedure_name;"); ...
21 Jul 2021 by Jeremy Likness
This article walks you through my project Planetary Docs, a repository that showcases a full application that supports Create, Read, Update, and Delete operations (CRUD) using Blazor (Server), Entity Framework Core and Azure Cosmos DB.
31 Aug 2021 by Richard Deeming
Try: .OrderBy(x => x.CustomProps.Where(p => p.Name == "Color").Select(p => p.Value).FirstOrDefault()) Or: .OrderBy(x => x.CustomProps.Where(p => p.Name == "Color").Select(p => p.Value).Min())
11 Sep 2021 by Sunggyoo Kim
Thank you, Gerry Schmitz and Richard Deeming for your replies. I found a solution to my question. As both of you mentioned, the problem was not the fact that a single DbContext has all tables in it. The problem was that I was using and passing...
3 Dec 2021 by Richard Deeming
I suspect it's because you're trying to join an in-memory list to a database table. Try: var topicIds = video.Tags.Select(x => x.TopicId).ToList(); var items = (from tag in _context.VideoTagLink.Where(t => topicIds.Contains(t.TopicId)) ...
9 Aug 2022 by Richard Deeming
Your ViewResult class represents the data for a single student. Your foreach loop would overwrite the properties of that class with the values for the last student returned. That is, it would do that, if your code compiled. But your code won't...
8 Jun 2023 by Richard Deeming
You have a combination of two settings which are causing this: entity.Navigation(e => e.Country).AutoInclude(); This causes the Country navigation property to always be included in any query that loads a Customer. ...
9 Jul 2023 by Graeme_Grant
Already answered here: How to store data on ASP.NET razor page using hidden field?[^]
24 Jan 2017 by Francesco Bigi
Hello!I have a created an MVC project, connected with my SQL management data base.When I execute my application, and try to login or create a new user I have an error:Server Error in '/'.Invalid column name 'Email'.Invalid column name 'EmailConfirmed'.Invalid column name...
24 Jan 2017 by Francesco Bigi
Thank you for you answer OriginalGriff;I created a new db an made again the project and now is working.It seem that I have modified too many times and it wasn't recognising the tables.:)
12 Mar 2017 by Steve Van Lint
Hello,I created a monitor system for our cloud environments.The environments are individual sites with their own database. Since each site has several tasks running, we need to intercept when a task fails. There are other things I monitor but the idea is the same.The situation is as...
12 Mar 2017 by Steve Van Lint
I have found a way to get this to work.The different db's are in the same domain and I have the necessary rights on all of them.What I will do is create linked servers as database objects.My main db will we db1 and I will use this to populate the tables with the errors.From db1 I...
1 Apr 2017 by Stein The Ruler
Hi! I have two classes; Item and ItemType. Item contains ItemTypeId and ItemType contains a list over Items. But the Items list never gets populated. Its always 0. Item: public class Item { public int Id { get; set; } public string Name { get; set; } public...
9 Apr 2017 by NalaBI
I found the problem it was with my database tables data types.
31 Jul 2018 by ParsleySage
EF Core 2.1 (using Razor Pages) I have a table, model and Razor Crud Pages to create new Examination schedules. The db table and model has a foreign key ID to an Examination Dates table and model, which in turn contains key dates that require adding/updating to an Exam schedule at various...
20 Feb 2019 by avelsamy
Hi, i have created the stored procedure which returns data from multiple tables. Here i i am unable(don't know) to call the stored procedure with parameter. Can anyone please help me to resolve this. I tried with one scenario its returns Id = 18, Status = WaitingForActivation, Method =...
20 Feb 2019 by Gerry Schmitz
How to: Execute a Parameterized Stored Procedure Using EntityCommand | Microsoft Docs[^] EntityClient Provider for the Entity Framework | Microsoft Docs[^]
26 Feb 2019 by Golden Basim
i created this view to calculate the total stocks of every item in every store as : CREATE OR REPLACE VIEW `view_items_stocks_smallest_unit_prices_noserials` as SELECT items.stitems_ID, items.stitems_Status, items.stitems_Name, items.stitems_Type, ...
26 Feb 2019 by OriginalGriff
See here: SQL GROUP By and the "Column 'name' is invalid in the select list because..." error[^]
23 Apr 2019 by Bohdan Stupak
I'm afraid you can't since Include loads all the data for your navigational property. If you are concerned with the amount of data loaded I would rather suggest you not to load the whole dataset in memory. Instead, apply some filtering to load only data you require. Also, consider learning about...
31 Oct 2019 by Richard MacCutchan
EF 3.0 in .Net - Google Search[^]
1 Nov 2019 by Richard Deeming
As you've discovered, you can't: Breaking changes in EF Core 3.0 - EF Core | Microsoft Docs[^]: Starting with 3.0, EF Core targets .NET Standard 2.1 and will run on all platforms that support this standard. This does not include .NET Framework.
31 Jan 2020 by ElenaRez
I’m implementing a project using asp.net core and I'm new in this field. Employing DB first approach and creating models in Visual studio, in SQl server I have two tables called API and Applicant that have many to many relationship and there is also their junction table called ApiApplicant....
31 Jan 2020 by Bertha Wwallace
var dbContext = new MyEntitiesDbContext(); var theApiapplicant = dbContext.Apiapplicants.Where(a => a.Id == myApiapplicantId).FirstOrDefault(); theApiapplicant.IsDeleted = true; dbContext.SaveChanges(); Have fun!
11 Feb 2020 by Gruja82
Is there an option to set OnUpdate to Cascade of ForeignKey using Fluent API? There is only for OnDelete behavior. What I have tried: modelBuilder.Entity() .HasOne() .WithMany() ...
15 Jul 2020 by Member 14637786
Hello, is there a good and fast way to get a single Parent object (or its id) by condition without iterating up all the levels of self-referencing relationship? The model is for example this (pseudocode): class MyObject { bool myCondition;...
14 Jul 2020 by #realJSOP
Your model makes absolutely no sense. 0) The MyCondition property doesn't appear to have any association with the specified question. 1) The ParentID property should be called ID because it's the id of the object, not the parent object.. ...
15 Jul 2020 by Richard Deeming
Are you free to modify the table structure? If so, you might be able to use a HierarchyID column. hierarchyid (Transact-SQL) - SQL Server | Microsoft Docs[^] It's not supported natively, but there's a third-party library which adds support to EF...
16 Jul 2020 by Torakami
The problem is that, in the group by I want the first result in the group by using first() or firstOrDefault() but I get an error saying Quote: could not be translated. Either rewrite the query in a form that can be translated, or switch to...
14 Nov 2020 by csrss
Hello everyone. This is my Entity, which is stored in database: public class Rule { [Key] public int ruleId { get; set; } public string name { get; set; } public int[] categoryIds { get; set; } } I...
16 Nov 2020 by csrss
Hello friends! Here are my entities: public class Subscription { [Key] public int id { get; set; } public string name { get; set; } public double data { get; set; } } public class...
19 Nov 2020 by Ahmed Dabas
I'm working with Repository pattern in my desktop project's , but i faced some problems with this pattern earlier i read many articles discuss that this pattern is dead so , i tried to find what's the alternative ? what is the suitable pattern...
19 Nov 2020 by Dave Kreskowiak
Why does there have to be a pattern? Once a newb here's the word "pattern", they typically forget about solving the problems in their code, forcing their code to fit a certain pattern and layers of abstraction instead of just forgetting about...
24 Nov 2020 by csrss
I think it should be something really simple, but cannot figure it out. I have a simple select query: .Select(company => company.clients .Select(client => client.policy != null ? new { name = client.name, policy =...
24 Nov 2020 by Dave Kreskowiak
When you write a LINQ query, you have to keep in mind that the query is not executed on the client machine. It it translated to SQL query language, then that query is sent to the server for execution and the result set returned. The problem is...
24 Nov 2020 by Richard Deeming
It depends on what shape you want for the returned data. I suspect the problem may be with the nested Select. Try: .SelectMany(company => company.clients.Select(client => new { name = client.name, policy = client.policy != null ?...
3 Dec 2020 by csrss
There are 2 tables: public class Info { [Key] public int id { get; set; } public int name { get; set; } public int surname { get; set; } } public class Client { [Key] public...
3 Dec 2020 by Richard Deeming
Cascade Delete - EF Core | Microsoft Docs[^] Assuming this is a one-to-one relationship[^]: protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity() .HasOne(c => c.info) .WithOne(i...
3 Feb 2021 by Richard Deeming
The property isn't missing; it's blank. There's nothing in the code you've shown which would modify the JSON data. The only explanation is that the string you're saving from your code does not match the string you're pasting into SQL Management...
7 Apr 2021 by nrramesh
select * from Table where CAST(FORMAT(column,'00.00') as varchar(20)) LIKE '%03.1%' Now, I have a IQueryable and want to send the Query through LINQ with the given format What I have tried: obj.Number.ToString("{0:0.00}")
7 Apr 2021 by Richard Deeming
Define the function(s) you want to call: public static class SqlFunctions { public static string Format(decimal? value, string format) => value?.ToString(format) ?? string.Empty; public static void Register(ModelBuilder...
21 Sep 2022 by Babar_Malik
I want to create a multi-tenancy web application with Asp.net Core and EF Core i.e. Separate SQL server Database per Tenant. I have a question, during migration how to handle DB updates i.e. if I have changed a model and added new fields or...
2 Jun 2021 by csrss
Hi. I am trying to understand this method for a whole day long now now. I need to call a stored procedure, which does not return, or at least does not suppose to return anything. Just like a void method call. However, no matter what I am trying...
2 Jun 2021 by Gerry Schmitz
Your query has nothing to do with EF; there is no relation between it and any EF entities; it's a simple C# SQL SP call. (If MyClassSet had elements, it might work, but that's only because you made your query dependent on it) sql server - How to...
10 Jul 2021 by Manos Kanellopoulos
Im using DDD in my project and I have an entity which belong to two bounded contexts with different properties each one. Both bounded contexts add records by this entity. How can I configure these two classes to map to same table by fluent Api? ...
10 Jul 2021 by #realJSOP
Try using the mapped entity as a base class for two derived entities.
31 Aug 2021 by Member 14637786
Hello, is this possible to write SQL-translatable query to order by a dictionary table? For instance: class Customer { string Name {get;set;} IEnumerable CustomProps {get;set;} } class CustomProperty { string Name...
11 Sep 2021 by Sunggyoo Kim
My question: what determines the speed(performance) of calling DbContext.SaveChanges() method? And is it a bad practice to put all the DbSets in a single DbContext? I have a c#/WPF/MS SQL Server/Entity Framework Core project, which is actually...
24 Sep 2021 by Sni.DelWoods
I have a custom DateTime-Range class which is used in several models: public class Entity { //... public DateTimeRange Usage {get; set; } //.... } public class DateTimeRange { public DateTime From { get; set; } public DateTime...
24 Sep 2021 by Sni.DelWoods
Solved. The anontation does the whole job: [Owned] public class DateTimeRange { public DateTime From { get; set; } public DateTime To { get; set; } } Output datatable is as exptected: Validity_From = ... Validity_To = ... ...
3 Dec 2021 by bindash
I am getting this issue at stage env only after making deployment and getting error at response. System.InvalidOperationException: Collection was modified; enumeration operation may not execute. at...
16 May 2022 by Mahfoud Bouabdallah 2022
I started creating a role-based security system in my WinForm application so I began with Form navigation (Permission Navigation) and this is my entity's public partial class User { public User() { UsersToRoles = new...
16 May 2022 by Mahfoud Bouabdallah 2022
I decided to go this way: When the user has successfully logged in, I catch the Id then I make a call to get all roles related to that user after that I make another call to get all permission navigation using role Id that I got earlier.
14 Jun 2022 by Anvarkhon Khamzaev
There are two entities Task and User. Task entity has two foreign keys (both int - id) Performer and Creator that is linked to User entity Id field. They are shadow properties, so in db their name are PerformerId and CreatorId. When I try to test...
1 Aug 2022 by Code4Ever
I use the following code to get paged data to the DataGerid: using (var _sqliteContext = new SQLiteContext()) { AssociatedObject.LoadDynamicItems(e.StartIndex, await _sqliteContext.Equipments ...
29 Jul 2022 by Gerry Schmitz
If you want to display the last page, retrieve the last page: .TakeLast( e.PageSize ); Enumerable.TakeLast(IEnumerable, Int32) Method (System.Linq) | Microsoft Docs[^]
1 Aug 2022 by Richard Deeming
You can't "reverse the order" of that data source, because you haven't defined any order for it. The data will be returned in whatever order the SQL engine chooses to load it. Whilst that might appear to be stable at the moment, it can and will...
25 Aug 2022 by Vikas Goswami0297
Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728 What I have tried: Startup.cs using BooklistRazorApplication.Model; using...
25 Aug 2022 by Richard MacCutchan
Design-time DbContext Creation - EF Core | Microsoft Docs[^]
18 Apr 2023 by xTMx9
Hello, I am currently facing an error when running a method that could be related to 2 connectoin instances running at the same time but I can't find how is it happening exactly. The error: InvalidOperationException: Cannot use multiple context...
18 Apr 2023 by Richard Deeming
Quote: I have checked the program.cs file and all services are registered as "Transient" in it. Well, there's your problem. Services registered as "transient" will have a new instance created every time they are resolved. You have two (or...
29 May 2023 by hardover
Basic situation is: Application manages a standard set of records for an organization. It will work on only one organization at a time. App must be able to create a new organization on request. App should be able to create a database for a...
29 May 2023 by Graeme_Grant
What you are trying to achieve is multi-tenancy. Here is a google search that will point you in the right direction: ef core multi-tenancy - Google Search[^]. First link returned: Multi-tenancy - EF Core | Microsoft Learn[^]
8 Jun 2023 by Mahfoud Bouabdallah 2022
I have three class GdsReceptionBlackProduct, Employee and Customer public partial class GdsReceptionBlackProduct { public int Id { get; set; } public string? CreatedBy { get; set; } public virtual Employee?...
28 Jun 2023 by xTMx9
Hello! I recently migrated to .net 6 and to a new EF version. The tree model in my code is not working as intended. In my data, I have several stores, several cities and several countries. They should be displayed as the following: --->...
28 Jun 2023 by Ralf Meier
I can't give you a complete code ... but a description how to do it ... You must iterate through your entries and create at first the Root-Nodes (and only them) - and for every entry look if the root-node is allready existing. After this you...
28 Feb 2022 by Richard Deeming
EF Core methods to call SQL Server's TRY_PARSE function
27 Mar 2017 by Tyler Rhodes
Reflections on writing a simple blog engine in ASP.NET Core with Entity Framework Core
4 Apr 2017 by Robert_Dyball
Covering conversion from Angular 2.40 to Angular 4.0 + Publishing the ASP.Net Core / Angular 4 SPA to IIS using VS2015.