Click here to Skip to main content
15,893,486 members
Everything / Entity Framework / Entity Framework 6.0

Entity Framework 6.0

EF6.0

Great Reads

by MarkLTX
Automatically implement INotifyPropertyChanged for every property in Entity Framework 6.0 entity classes
by DiponRoy
How to manage Entity Framework Code First in Real Time Projects
by Emiliano Musso
In this article, we will see how to use entity framework in our Applications, developed through the various languages that Visual Studio allows us to use. The examples in this article and probably in the next, will be C # used under WinForms, but - as mentioned - this choice is not going to affect a
by Vahid_N
It's easy to forget not disposing object contexts, which leads to memory leaks and also leaves too many related connection objects not disposed as well.

Latest Articles

by Herman.Instance
Migrations does not apply to T-SQL rules for ALTER TABLE ALTER COLUMN
by Akhil Mittal
Code First Approach and Migrations in Microsoft .NET Entity Framework
by MukeshKumarTech
This article will explain how to perform CRUD (Create, Read, Update and Delete) operations in ASP.NET Core Web API using Entity Framework Core.
by Vincent Maverick Durano
This article is part 1 of the series for building a simple web application in ASP.NET MVC 5.

All Articles

Sort by Updated

Entity Framework 6.0 

N 24 Apr 2024 by Golden Basim
MySQL Database contains huge data (more than 5Gb) and more than 300,000 of records in some table. Some Queries require to handle some of fields value before showing it to the user like this query : var pQuery = DB2.sales_main ...
20 Apr 2024 by Graeme_Grant
So the issue is the uniqueness of the key. Using a dynamic object is the cause of your issue. Each object is unique. This is easy to demonstrate. Create two instances of a class with the same values, then do a comparison. You will find that they...
20 Apr 2024 by Golden Basim
I need to get the latest purchases cost for every group based on Item , supplier, unit. and synchronization it to another location .. item 1, pack, Jone, ... item 1, pack, Mich, ... item 1, pack, Yasser, ... item 2, pack, Jone, ... item 2,...
12 Aug 2023 by Sandy Safwat
Please make sure from the starting host : the api project is selected from the package manager console, make sure the persistance project is selected
12 Aug 2023 by Sandy Safwat
Hi Am trying to create a database from existing migration persistence database public CMSDBContext(DbContextOptions options) : base(options) { } //Dbsets protected override void...
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 {...
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...
14 Mar 2023 by soufi web
Hi I want to move or (copy to t2 and delete from t1 )all data from table1 to table2 using Entity Framework, they have the same fields, and most of the answers talk about .Core or asp.net. I'm using EF6. Please Help me Thanks a lot What I have...
3 Dec 2021 by Richard Deeming
You've created both a one-to-one relationship (by convention) and two one-to-many relationships (by configuration). That's definitely not correct. Based on your description, you need: public class BuySellHouse { public int Id { get; set; } ...
2 Dec 2021 by 4L4K1
according to the code in what I have tried section BuySellHouse is parent EstateImages is child I tried to create a 1 to 0/1 relationship. I am not sure I did it correctly inserting parent with child by code like this gives me an error ...
22 Nov 2021 by Tshumore
I have an EF6 MVC application which I intend to do update operations but I am having issues on 1) how to edit Dropdown values 2) how to edit Date values 3)Assign default values for edit properties I am able to create an AssetRequest entry as...
2 Nov 2021 by Herman<T>.Instance
Migrations does not apply to T-SQL rules for ALTER TABLE ALTER COLUMN
6 Jul 2021 by JOTHI KUMAR Member 10918227
hi to all, How to disable Migration entity framework bcz in my project database is automatically created for given datacontext name so kindly send me code how to disable Migration and refer my own database in my tablemy mail address:- [email removed]
29 May 2021 by Ms Dinosaur Bamboo
Dear all, I try to run my CRUD application for multiple model of Admin information on datatables using JavaScript + EF MVC but not luck to see result successfully. I am surfing net , read many the forum and also follow step from youtuber but i...
30 Nov 2020 by Golden Basim
how to insert large records into table (purchases_item) using EF6 AddRange and return the IDs to use it using add sub table (stock_noserials). Data Samples: i have this gridview: ------ name --------- stock --------- price ---------- others...
30 Nov 2020 by Richard Deeming
Not clear without seeing your model, but the general trick is to use the navigation properties to associate the two entities. Entity Framework will then be able to automatically update the foreign key property with the generated ID of the...
13 Sep 2020 by Gerry Schmitz
...OrderBy( o => switch( o.Status ) { case "Accepted": return 1; case "Pending": return 2; ... default: return 6; } ) .ThenBy ... etc.
13 Sep 2020 by Golden Basim
hi, my project was created using c# & entity framwork 6 i have this table (entries) that have status filed the status filed will fill with one of this values : Pending,Accepted,Rejected,Delayed,Completed i want to retrieve all the record sorted...
12 Sep 2020 by Member 14892534
I am looking for solution to the issue of insert new or delete of a datagrid row that is not being identified or captured by simply checking dbcontext.changetracker.haschanges status. HasChanges picks up when user modifies existing datagrid row...
12 Sep 2020 by Gerry Schmitz
Too much "coupling". The Observable Collection doesn't interact with the data context. You add event handlers to the OC (i.e. CollectionChanged) that interact with the data context. The entities in the OC should be "detached" from the DbContext...
10 Jun 2020 by Enobong Adahada
Please how do I assign table name to generic DBSet base on Model? I want to create a table for every registered user, using their userId and the table name in EF6. public class ContactModel { [Key] [Required] ...
10 Jun 2020 by Richard Deeming
That's a terrible idea! Create a single table for your contacts, and add a foreign key relationship with the users table. public class User { [Key] public Guid Id { get; set; } public virtual IList Contacts { get; set;...
6 Jun 2020 by Golden Basim
hi, i created new project C# & EF6 (Database First), but after some times i need to update the tables ( add new tables , Fields , delete Fields) What I have tried: in this time i use MySQL Query to do that , but i ask if there are any method...
6 Jun 2020 by Dave Kreskowiak
No. You can use one or other, not both in the same project. For a new project using Code First, EF will automatically create the tables for you from the DbSet entries in your DbContext implementation.
5 Jun 2020 by Maciej Los
I think that no one is able to help you due to the fact that EF configuration should be done in several places. I'd suggest to read official MySQL tutorials: MySQL :: MySQL Connector/NET Developer Guide :: 6.6 Tutorial: Using an Entity Framework...
5 Jun 2020 by Golden Basim
hi, based of my previous Question answers. and 2 day of search i decide to change my old approach that i use for setting a custom connection parameters. but i still have some issues, i preferred to create separated question because i thing it...
3 Jun 2020 by Golden Basim
hi, some times (5-10%) when i try to execute EF Query this error appear : System.Exception: خطأ عند محاولة ملء مصدر البيانات. تم طرح الاستثناء التالي: Failed to connect to the database. To learn more, see the exception details. Exception...
1 Jun 2020 by Maciej Los
There's 2 possible ways to set up EF configuration: 1. Code-based configuration - EF6 | Microsoft Docs[^] 2. Configuration File Settings - EF6 | Microsoft Docs[^] If you're using code-based configuration, then... Quote: A class derived from...
9 May 2020 by Golden Basim
how to insert this datetime value to DB using EF 31/12/2021 11:59:59 PM (end of the day in the year) 1- i created this field fiscal_year_end and its datatype is DATETIME. 2- now i trying to update the record with the value fiscal_year_endvar DB1...
25 Apr 2020 by Gerry Schmitz
You're probably missing part of the "data" story and overriding a (duplicate) "key" with the IDENTITY function you're triggering with the "Key property".
8 Nov 2019 by Richard Deeming
Another option: account_Funds.RemoveAll(f => trsBalance(f.accfunds_ID) == 0); List.RemoveAll(Predicate) Method (System.Collections.Generic) | Microsoft Docs[^]
8 Nov 2019 by Golden Basim
i try to fetch the data (funds data) and filter the results with its balance but this error appear : System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute.' at foreach (account_funds f in account_Funds) What I have tried: public...
7 Nov 2019 by phil.o
You cannot enumerate a collection in a foreach block and modify the collection in the same block. Usually the solution is to get back to a plain old index iteration, starting from the end of the collection. In clear, changeforeach (account_funds f in account_Funds) { if...
7 Nov 2019 by F-ES Sitecore
Rather than executing account_Funds.Remove(f); keep a collection of all the items you want to remove; var toRemove = new List(); foreach (account_funds f in account_Funds) { if (trsBalance(f.accfunds_ID) == 0) { toRemove.Add(f); } } after...
13 Aug 2019 by istudent
Quote: My application is using EF6 Code First approach. I have a poco class Employee with three properties Id, Name and Salary and this class is derived from base class with properties created and modified date. This class has been already migrated and have table in Db with 5 columbs namely,...
13 Aug 2019 by Richard Deeming
The only way to change the order of the columns is to recreate the table. But it's really not worth it - the order of the columns in the table doesn't make any difference to performance, or to the behaviour of Entity Framework. The only time it would make any difference would be if you issued a...
19 May 2019 by Ameer Adel Al-Zubaidy
Hello I am on my first EF6 project and I have couple of questions Project outlines Property (Building) have Rooms A Room have list of criteria or rating Each criteria own a set of values i.e. Property (Building) A have Room 1 Each room have bunch of values Value a 0-1...
19 May 2019 by Ameer Adel Al-Zubaidy
Right first of all sorry for the rough English, I am a mess right now the solution is as follows: Loop through the existing Main categories (Property(Building)) for Property.Count Property[i].Rooms = inProperty[i].Rooms So on and so forth for the other nested lists ...
2 May 2019 by johannesnestler
What Dave said is kind of true and for real big data import worth a try. I just wanted to notice that I offer an AddRange method on my Repository-Impl and do DataContext.Save only once - so for normal use cases a practical way - Btw. Never look at EF Performance in Debug, without Pre-JIT or if...
2 May 2019 by Member 14119435
Hi. I am working on a project that use unit of work and repository pattern with orm EF6. i want insert a list of object about 800k record into database. i send every 15k or 10k record to instance of repository and then commit it. it is too slow. how can i give more performance? i dont want to...
2 May 2019 by OvrLrdFregus
Hey all, I am having an issue with Code first on EF6. I get this error when trying to create a migration "The number of properties in the Dependent and Principal Roles in a relationship constraint must be identical." Here is the code: public class TradeJournal { [Key,...
2 May 2019 by Dave Kreskowiak
You can't really improve the performance using plain vanilla EF. No matter what you do, EF is always going to do one INSERT at a time for each item you're adding. There's no way to speed that up. I would suggest stepping outside EF for this and using the SqlBulkCopy[^] class instead. You're...
27 Apr 2019 by Gerry Schmitz
You have a one-to-one relationship according to you classes. Entity Framework – mapping references with composite keys | Feb dev[^] c# - Entity Framework Code First One to One relationship on composite key - Stack Overflow[^]
17 Apr 2019 by RuiBarreiros
Hi, I realize my question is a little bit conceptual, but I need this sorted before I move on with my project. I've created dozens of views in SQL, some of which are pretty complex involving more than 12 tables. I use these views in a business report excel file to do some business...
17 Apr 2019 by Christian Graus
Presumably you created those views to simply access to sets of data that resolve specific problems in your domain. So, keep them.
15 Apr 2019 by Golden Basim
i try to show xtrareport , this report was binding to SP using Framework, but this error appear during creating document . report.CreateDocument(true); DataRetrievalException: خطأ عند محاولة ملء مصدر البيانات. تم طرح الاستثناء التالي: Ambiguous match found. this line "خطأ عند محاولة ملء...
15 Apr 2019 by Maciej Los
Please, refer this: Use Stored Procedure in Entity Framework[^] The most important thing is that, that you need to set "Import selected stored procedure into entity model" to create complex type and return all fields as a result. Note, that "Balance" field is calculated on "Debit" and...
15 Apr 2019 by Golden Basim
hi, i created this view : CREATE OR REPLACE VIEW `view_items_accounts_tree_with_date` as SELECT Acitems.accitem_AccID, acc.accdet_Cat, acc.accdet_AccountCode, CONCAT_WS(' - ', acc.accdet_AccountCode,...
4 Apr 2019 by Richard Deeming
It looks like you've created an entity type to represent the values returned from your view, and you've set the Count column as the primary key for that type. EF uses the Identity map pattern[^]. When it tries to load the third row (Count = 2), it thinks that it has already loaded that record....
4 Apr 2019 by Golden Basim
hi, i have MySQL VIEW : (4 record) sDate , Count , Amount 2019-04-01, 2, 600.0000 2019-04-02, 1, 4000.0000 2019-04-03, 2, 1400.0000 2019-04-04, 1, 3500.0000 i try to show this data in Gridview using EF6 var Purchases = DB1.view_purchases_amount_per_day.Where(x => x.sDate >= FirstDayOfMonth...
3 Apr 2019 by #realJSOP
0) Your linq query makes no sense because EVERY day is between the first/last day of its month. Maybe you meant to compare just the month? (We can't see what the vars LastDayofMonth and FirstDayOfMonth are, but I assumed they're a datetime.) Maybe better names would be StartDate and EndDate? 1)...
26 Feb 2019 by OriginalGriff
See here: SQL GROUP By and the "Column 'name' is invalid in the select list because..." error[^]
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, ...
3 Oct 2018 by nuthi_naresh
I want to upload Excel file from Webpage and save the data to SQL database and then retrieve the data from db to display in tabular format USING Entity Framework in MVC Sample Data for Attendence SL. No Student ID Student Name NIOS EnrolmentNo. Date What I have tried: S2Entities4...
3 Oct 2018 by Richard Deeming
Your sample data has the column name "Student Name". You are trying to read the value from a column called "Student_Name". Those are not the same. The first has a space, whilst the second has an underscore. Similarly, "NIOS_Enrolment_No" is not the same as "NIOS EnrolmentNo.". The column...
3 Oct 2018 by #realJSOP
If it doesn't have to be a real-time process, you could create an SSIS package to import the uploaded file, create a SQL server job to run the package, schedule that job to run every N minutes, and simply let the user hit refresh on the web site whenever he wants. I know it sounds like a lot of...
19 Sep 2018 by Hakan Bayrak
You can look here also: Update an Existing Database using Code First Migrations with ASP.NET and Entity Framework[^]
19 Sep 2018 by AbhishekDotNet
Hi,I have a created two separate C# web application using EF6 (one with Database First and other with Code First approach). everything is going on smoothly but after sometime it is required to merge both.After merging , Database is same for Code First Approach.Initial I was using...
11 Sep 2018 by MukeshKumarTech
This article will explain how to perform CRUD (Create, Read, Update and Delete) operations in ASP.NET Core Web API using Entity Framework Core.
17 Aug 2018 by Dave Kreskowiak
You never gave any details about your database schema as coded in EF, so this is just a guess. What you're seeing is the expected behavior. You are NOT supposed to make any changes to a column tagged [Timestamp] in EF. Timestamp fields are entirely managed by EF. They are used to manage...
17 Aug 2018 by Herman<T>.Instance
Hi Folks, in my ODATA service I use EF6 to work with SQL Server. An EDMX is created also for the table Departments. In that table there is a TimeStamp field for Concurrency purposes. And yes I have added [Timestamp] data annotation in the code. And in the EDMX the field is FIXED for Concurrency...
18 Jul 2018 by Member 12852443
Data is not inserting into DB, How handle composite primary key, where one PK is set to auto-increment. Here not entering any data into Id column , but it throws following exception . "Cannot insert explicit value for identity column in table 'TableName' when IDENTITY_INSERT is set to OFF." ...
18 Jul 2018 by Gerry Schmitz
A table cannot have more than one "primary key". EF can only recognize one primary key; either a single value or a compound key. Anything else would be a "secondary key / index"
4 Jul 2018 by Member 13898412
I was using Moq with my project. So I installed it and then installed its dependencies. There is a chance that you are some dependencies.
4 Jul 2018 by Andrew797
I started developing an MVC app on my laptop, which was running VS2013, and SQL server 2008 R2. I copied this project over to my desktop computer running Visual Studio 2013, SQL server 2012 Developer Edition.When I run this MVC app from my Desktop, I get the following error on the line...
3 Jul 2018 by Vincent Maverick Durano
This article is part 1 of the series for building a simple web application in ASP.NET MVC 5.
3 May 2018 by Måns Tånneryd
Extending the entity framework with bulk operations for both inserts and updates
3 May 2018 by Måns Tånneryd
How to extend the Entity Framework with bulk insert functionality, using DbContext
2 May 2018 by Member 12489631
Can someone please advise me how I can get PropertyChanged.Fody to work with WPF databinding and EF 6.0 Database first? I am not using MVVM. I have an EF generated class called "Test" as follows.... //------------------------------------------------------------------------------ //...
6 Apr 2018 by CyberMakarov007
SQL table dependency with entity framework in WPF
7 Dec 2017 by Ben Hall (failingfast.io)
How to use FakeItEasy with Entity Framework 6
25 Nov 2017 by Code Atom
I m facing a problem, I have API that sends a request with a list of email addresses, now what system does it check each email address from the database, if it exists then it ok we use userid else we create a new user. The problem arises when we send multiple requests with the same list of...
5 Oct 2017 by Herman<T>.Instance
I have a EF Entity (based on a table) that hold column names like var1, var2, var3 How can I map the properties very simple to row[0], row[1], row[2]. Where row is a DataRow. My biggest problem is that the Datatable object does not allways have the same number of columns. My code: private...
5 Oct 2017 by Thomas Nielsen - getCore
This is a bit crude and could require som nullchecking but this should work :) public class RowMapper { /* The way i read your sample is you get a datatable with columns and rows, these are to be mapped to an entity which presumably doesn't require all...
19 Sep 2017 by SlavaUtesinov
Practical guidance how to use Effort library in your unit tests including workaround with views and triggers and some pitfalls
29 Aug 2017 by Janine_A
I have an mvc5 application that is connected to a EF database. Some fields in this database are meant to be autogenerated as declared in SQL, but when used in MVC and upon inserting records, the GUID only contains the value of 0 for all records. How can I resolve this? Any help will be...
1 Jun 2017 by Sherjil_Ahmed
Mixing DB-First and Code First Approach for using SPs in EF-Way
1 May 2017 by Roshan Choudhary
Handling data concurrency in Entity Framework 6 with Database First Approach.
30 Apr 2017 by Wendelius
This article explains the problem, when another transaction (concurrent or not) accidentally overwrites previously modified data and how to prevent this from happening.
24 Apr 2017 by SlavaUtesinov
Implementation of "insert" repository with dynamic database table (re)creation, if it not exists. It is possible to specify which migrations will be used for that otherwise will be used default creation logic. Usage example - dynamic logging and archivation or manual table creation for some purposes
22 Apr 2017 by srilekhamenon
Dear friends iam getting the error 'System.Data.Entity.DbSet`1' does not contain a definition for 'ToList' and no extension method 'ToList' accepting a first argument of type 'System.Data.Entity.DbSet`1' iam getting the error here, how to...
2 Apr 2017 by Wendelius
This is an alternative for "What You See Is What You Update"
28 Mar 2017 by VICK
Facing a strange problem with EF at the moment. I have a table in database with nvarchar(MAX) data type and is a nullable field. While updating the entries in the table when I assign null to this field its not saving that null, rather keeping the old value intact. But saving the empty string in...
9 Mar 2017 by Member 11040029
I am learning EF. While practicing I noticed a strange behavior for Lazy Loading.I read, Lazy loading is enabled by default and can work only if navigation properties are marked virtual along with LazyLoadingEnabled = ture in context's configuration.So, I decided to turn off lazy loading...
9 Mar 2017 by Richard Deeming
I suspect that this is because you're using self-referencing navigation properties, and loading the entire set into memory.I can't find the equivalent documentation for EF6, but the EF Core documentation has a note that would explain this behaviour:Loading Related Data | Microsoft...
8 Mar 2017 by F-ES Sitecore
Disabling lazy loading doesn't stop related data loading, it stops it being loaded on-demand, so instead it is loaded right away. You might be better using the "Include" feature to dictate what data is lazy-loaded or not on a per-case basis. It will make it explicit what is being lazy loaded...
6 Mar 2017 by Michael Doleman
A simple DAL with an integrated, lightweight model for database seeding from a JSON source, using the code-first method in Entity Framework.
22 Feb 2017 by Member 11748288
hi i want change Property Name in EF Entity to create Custome XML with Web Api.my entity ispublic partial class foo{ public int ID{get;set;} public string Name{get; set;} public string LastName{get; set;}}and created Xml is Ali ...
22 Feb 2017 by Graeme_Grant
I hear that you don't want to decorate your classes with attributes but to do it totally POCO, there is a bit more work involved. Check out Sam's Flickr.Net Lib. Here is how he does it with his Photo Class: flickr-net/Photo.cs at master · samjudson/flickr-net · GitHub[^]. My preference...
22 Feb 2017 by Valery Possoz
Hello,You just need to decorate your class. [DataContract(Namespace = "")] public partial class foo { [DataMember(Name = "code")] public int ID { get; set; } [DataMember(Name = "Firstname")] public string Name { get; set; } ...
13 Jan 2017 by ahmed_sa
I need to build web site by .net web technology asp.net mvc USING C#But i confuse What is best for build Web site Implementation by MVCUsing Entity framework(build database and create modules automatic by EF)ORImplementing web site by using Code First ?What I have...
13 Jan 2017 by Dave Kreskowiak
Code First is a mode that Entity Framework works in. It is something to implement a web site. Entity Framework is an Object Relational Mapping tool. It automates a lot of the work to save data model objects to a database and reconstitute them back into objects from the database.Entity...
13 Jan 2017 by Peter Leow
Check this out: entity framework - Code-first vs Model/Database-first[^]
7 Dec 2016 by Kuv Patel
Convert a class library of POCO classes to datacontracts for use with WCF without having to write DataContract and DataMember attributes directly to the POCO classes.
27 Nov 2016 by SrikantSahu
I am trying to bind a gridview using EF 6.0 raw Sql query with Async, but the system goes on for endless execution and task.Result is never populated.What I have tried:protected void Page_Load(object sender, EventArgs e) { var task = LoadDataAsync(); task.Wait();...
27 Nov 2016 by Dave Kreskowiak
Your code is essentially single threaded. You've got 2 threads, but one is completely blocked waiting on the other. In any case, putting the LoadData code on a background thread, since it's the only thing you're doing, is no different than if you completely skipped all the Task/async/await...
10 Nov 2016 by MammadovAdil
Automatically define state of entity graph for EntityFramework Code-First using a single line of code.
7 Nov 2016 by Wahid Bitar
Validated the unique constraints at dbContext ValidateEntity in a generic way by reading the IndexAttribute values.