Click here to Skip to main content
15,892,298 members
Everything / CodeFirst

CodeFirst

CodeFirst

Great Reads

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 DiponRoy
How to handle database scheme changes with normal SQL scripts, without migration in Entity Framework code first
by Nathan Minier
Generic AddOrUpdate for EF with composite key support

Latest Articles

by DiponRoy
EF Core first publishing multiple DB contexts in same DB
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
by Kelum Priyadarshane
This project developed using combination of Entity Framework 6.0 + Code First Approach + Web API 2 + Repository Pattern + ASP.NET MVC 5 + SQL Server 2012 + Unit of Work Testing + Bootstrap.
by Farhad Jabiyev
One of the most popular questions is whether there exists a method which will automatically decide whether to insert, update or delete entity in the Entity-Framework. Now it is possible with EntityGraphOperations library.

All Articles

Sort by Score

CodeFirst 

28 Jul 2014 by DiponRoy
How to manage Entity Framework Code First in Real Time Projects
10 Jun 2016 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
30 Jul 2014 by DiponRoy
How to handle database scheme changes with normal SQL scripts, without migration in Entity Framework code first
20 Sep 2016 by Karthik_Mahalingam
Quote:"Cannot insert explicit value for identity column in table 'table name' when IDENTITY_INSERT is set to OFF."straight forward issue.Id is an identity column, you cannot explicity insert identity value to the table directly,You will have to set the IDENTITY_INSERT to ON to insert...
23 Aug 2017 by OriginalGriff
You added it to the class, but you don't appear to have a matching column in your database. As a result, SQL cannot handle any requests you make to that column. Add the column to the DB...
7 Feb 2013 by Mike Meinz
You need to keep history. Perhaps indefinitely. You need a "logical" deletion flag usually a Bit data type column with a name like "ActiveProduct". An active product that customers can buy would have the ActiveProduct column = 1. When a product is to be deleted from the current product...
20 Jun 2013 by BobJanova
I'm not a WPF expert so I can't give you working code, however I can tell you the approach to use here.The view for a set of results should be a ListView, with the ItemTemplate set to whatever you want the display for an individual Vinyl to be (probably a panel of some kind with some text...
10 Aug 2016 by Nathan Minier
Generic AddOrUpdate for EF with composite key support
7 Feb 2013 by RobNO
Hi All,I am currently facing a little bit of a delima. You see I have this product/shopping cart/order system. In this system I have the OrderDetails table coupled to the Product table with a relationship of One Product can have many OrderDetails.If a user wanted to delete one of their...
3 Apr 2014 by Alcides Melo
I want to drop some tables and create again following my models design. But the CodeFirst never do it, keeping trying to apply the changes that I did, but for some reason he can't. The Designs of models class is ok but the tables on SQL is not and thats why and want to drop and recreate again. I...
4 Apr 2014 by Er. Puneet Goel
Just Start from this : Entity-Framework-Sample-Application-for-Beginners
5 Apr 2014 by Dave Kreskowiak
Google for "entity framework 5 code first migrations" and you'll find what you're looking for.
15 Jul 2014 by Yogesh Kumar Tyagi
Use jquery multiSelect dropdownlist http://www.aspdotnet-suresh.com/2014/03/jquery-multiselect-dropdown-list-with-checkboxes.html[^]http://www.erichynds.com/examples/jquery-ui-multiselect-widget/demos/[^]
20 Aug 2014 by Eduard Keilholz
Have you seen this article? Seems to serve exactly your needs:Membership and Role providers for MySQL[^]
30 Oct 2014 by Duncan Edwards Jones
It does - so long as the account in the connection string has the kind of access required to create tables and so on... (Personally I don't like it to have that access so I tend to create/update the database independently of the application)
25 Nov 2014 by OriginalGriff
ICollection is an interface, List is a class.Which means that the first definition can take any class which implements the ICollection interface (which supports methods such as Add, Remove, and so forth: http://msdn.microsoft.com/en-us/library/92t2ye13(v=vs.110).aspx[^]) where List...
4 Mar 2015 by Richard Deeming
The result of calling:db.Books.Select(a => new { a.Title,a.Author})is an IEnumerable. There is no built-in conversion operator to turn that into a DataSet.Fortunately, it's not too hard to write one yourself:using System;using System.Collections.Generic;using...
5 Jul 2015 by Atish Dipongkor
Is this because the Trips have layover and the layovers have a reference back to Trips?http://stackoverflow.com/questions/17313632/self-referencing-loop-detected-getting-back-data-from-webapi-to-the-browser[^]
6 Jul 2015 by 9000605667
this solution will use full when my front end is in MVC. But my Front end is Angular JS. So it will not resolve the issue. But i fix this issue by changing the access specifiers of Trip in Layover class from public to private.Thanks for your solution..
26 May 2016 by Dave Kreskowiak
First you haven't shown us your DbContext and your configuration, so it's pretty much impossible to tell you where you went wrong. But, by what you have posted, i think you're over-complicating things.Next, all of these types will end up in the same table, Orders. Your discriminator for Lab...
17 Jul 2016 by nilesh sawardekar
c# - How to store variable 2D array via Entity Framework? - Stack Overflow[^]Have a look at this link
7 Aug 2017 by Dave Kreskowiak
Sooo...you've got some incrementing ID number or date/time stamp on these records to tell you which record was the last one inserted into the database, correct? You can't do this without it.
24 Aug 2017 by Thanks7872
Go through this : Adding a New Field to the Movie Model and Table | Microsoft Docs[^] You will get the idea about what is happening and why it is happening.
4 Sep 2019 by BillWoodruff
Consider posting on these CP forums: [^], [^] This a C# forum.
22 Apr 2020 by ishan_shah
In the migration, You should add your index creation to the up() method and a drop statement to the Down() method to enable downgrading the database schema namespace TestLib.Migrations { using System.Data.Entity.Migrations; public...
1 Aug 2012 by Oleksandr Kulchytskyi
i have resolved this issue by myself.The main reason , why this wont work , hide in realization of property:public string Speciality { get; set; } As concerns this property i have change it type to, see below:public IEnumerable Specialty { get; set; } and changed a bit my...
5 Dec 2012 by Member 3212080
I am developing an ASP.NET MVC4 application with EF Code First. I am having a many-to-many relationship among following classes. I have defined relationship using EF fluent api in my context class. But I am getting an error as it is trying to insert values into one of my master table involved in...
6 Dec 2012 by Member 3212080
I am developing application which will be used by Students, Providers, Administrator, Agents, etc. I am creating a Users table in database where login information of each user of the system (Agents,Students,Providers etc) will be stored and their respective fields (like firstname, lastname, etc)...
25 Dec 2012 by sasolanki007
Well you can go in following manner :->First of all add and entity model (edmx) in your solution->Add your tables into that edmx->Give relationships to tables->Now you can generate POCO classes by selecting option "Add Code Generation Item" ->Then you can Generate Database...
25 Dec 2012 by Oleksandr Kulchytskyi
Hi use VS addin's either EF productivity tools or EF Power Tools, after this tool is being installed,make reverse engineering with help of this tools.(POCOs and DbContext will automatically be created)
21 Jan 2013 by Ryanm1324
Does Entity Framework Code First work with Oracle Data Access Components? Can I use a model that was first used with SQL Server to generate a database in Oracle in the same way?
5 Feb 2013 by dedo1991
Dear programming community,I have the following problem when using code first migrations in my MVC3 web application.Patient Model:public class PatientModel { [Key] [Required(ErrorMessage = "Patient ID is required!")] [Display(Name = "Patient ID:")]...
10 Feb 2013 by Zoltán Zörgő
Here it is, my final suggestion now as answer:At the end of PatientModel you had:public SalutationModel Salutation { get; set; }just add "virtual":public virtual SalutationModel Salutation { get; set; }The typical convention when you need just a reference to the external entity...
23 Feb 2013 by astuserp
I need to perform the following, in EF CodeFirstRetrieve a record, Delete it.Do other tasks.If other tasks are done successfully, the deletion needs to be commited.Otherwise, the deletion needs to be rolled back as if the record has never been deleted before.Does anyone has a...
23 Feb 2013 by Dave Kreskowiak
There's nothing special about this. When you Remove the record from EF it's just TAGGED to be deleted. It won't be deleted from the database until you call SaveChanges on your DbContext. So, if you don't want the record to be removed, just change its state back to Unchanged: ...
16 Jul 2013 by ♥…ЯҠ…♥
Hi Friends,I want to implement code first approach in my project, but am using ASP.Net Webapplication.I have implemented Code first approach in MVC earlier but I want to know whether it is possible to implement the code first approach in asp.net web application without MVC.If it can be...
22 May 2013 by Zoltán Zörgő
Tricks? What tricks? "Code first" is an approach is related to Entity Framework, which is fully independent of other layers of the application: you can use it with WPF, Windows Forms, MVC, Console application and of course Web Forms too. Skip the MVC tutorials and see the other ones here:...
21 Jun 2013 by TeacherDean
Good morning everyone, I really need some help.I started this little project to help me study, while I am reading through O'Reilly's Code First book. I understand how to create a database and I can also populate my table with data that I provide from a WPF application, namely a few...
9 Aug 2013 by je-wo
I built up a class called Project:[Table("Projects")] public class ProjectProfile { [Key] public int ID { get; set; } public string Name { get; set; } public string Description { get; set; } public virtual ICollection HeadOf { get; set;...
9 Aug 2013 by vyas_pratik20
Hi , to do so you should use LINQ, you can not assign this directly
17 Sep 2013 by Member 10197079
how can we create Database looks like as follows in EntityFramework CodeFirst Appraoach:Note:I have created identity auto incremented by two and it is foreign key for all table.How can we write FluentAPI for foreign Key and unique key?Create Table [dbo].[UserAccount]([UserID] int...
21 Nov 2013 by Gianluca Palmieri
Hi!! I have a problem to update my db entities using code first approach. This is the model scenario: public class Book { public int Id { get; set; } public string Title { get; set; } public virtual Encyclopedia Encyclopedia { get; set; } ...
28 Nov 2013 by Member 10370658
Hello in my sample project ,i have created a model with EF Dbcontext class.But it is not initializing or reflecting in the Controller Class.I am using Asp.net MVC 3 razor ,EF DataFirst to bind database.In my other sample application it works fine.My Model Code
28 Nov 2013 by Member 10370658
We have to declare the class outside the model classLike BelowQuote:using System.Collections.Generic;using System.Linq;using System.Web;using System;using System.Data.Entity; namespace InformationManagementSystem.Models{ public class Information { public...
13 Jan 2014 by Brady Kelly
I'm trying to query a data model built on EF, but any and all queries I run throw an exception that states The item with identity 'Id' already exists in the metadata collection.Googling this yields very little useful information, except that for some databases, like DB2, the data...
12 Jul 2014 by NorouziFar
hi how can i create One-to-One Relationship in First Code?i did this , is it true or Not :ProjectMap.cspublic class ProjectMap { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public int ProjectId { get; set; } public string Name {...
29 Aug 2014 by DiponRoy
Hi,have a look at this, One to zero/one relation in entity framework code first[^]
30 Aug 2014 by Sandeep Singh Shekhawat
Both tables can have only one record on either side of the relationship. Each primary key value relates to only one record (or no records) in the related table. Keep in mind that this kind of relationship is not very common and most one-to-one relationships are forced by business rules and don't...
13 Oct 2014 by Pakorasu
Connector/Net 6.9.X version already has the support for it, see the following Link:How To: Using SimpleMembershipProvider with MySql Connector/Net[^]
30 Oct 2014 by Marc Clifton
I've been reading through this[^] and I don't have a clear picture of whether the database migration happens automatically when the application "starts up" if I don't use Azure as the host provider.Currently I'm using WinHost, and there's no "console" that I can open to do things like force...
12 Nov 2014 by Aleksandr Kotelnikov
Hello. I have some trouble with add additional field in table, which Entity Framework created for me to solve many to many relationship.Let's start from beggining.I have 2 classes (models):public class Craft { public int CraftID { get; set; } public string Name {...
25 Nov 2014 by Vishal Pand3y
I Have a model Lets say Customer and Products and this is one to many between Customer and Products ie one customer can have multiple products Now what is difference between public class Customer{public int Id { get; set; }public int Name{ get; set; }public ICollection...
25 Nov 2014 by Kornfeld Eliyahu Peter
ICollection is an INTERFACE, where List is a CLASS that IMPLEMENTS that specific INTERFACE!So the second option is bonded to the type 'List' where the first option can work with any type that implements the ICollection interface...
25 Nov 2014 by CPallini
Please note, your code wouldn't compile (you need to give a name to your ICollection or List property).In the first case, e.g.public class Customer{public int Id { get; set; }public int Name{ get; set; }public ICollection ProdColl{ get ; set ;}}You may use any of the...
26 Dec 2014 by SreerangaPrasad sane
My entity classpublic class person { public int PersonId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public virtual ICollection courses { get; set;} } public class...
28 Dec 2014 by George Jonsson
This part of the code will give you this problemif (john.courses == null){ john.courses.Add(stoptalk); john.courses.Add(rails); db.Persons.Add(john); db.SaveChanges();}because if john.courses == null is true, the Add operation cannot be executed as no instance of...
2 Mar 2015 by hamid025
I want to create a software for a library. for connection to database i used Codefirst overfolw.I have a form in my project that user enter server name and user id and password in it.Now I don't Know that where my connection string to save.if I save connectionString to web.config or...
2 Mar 2015 by Alex Sanséau
In your scenario, you want to create the connection string at run time, based on the user input. So storing the connection string in the web.config file is not a good solution, espectially for a web application where you are going to have multiple users accessing your application at the same...
2 Mar 2015 by F-ES Sitecore
Store your connection string likeAccess it likestring con =...
4 Mar 2015 by hamid025
hello.I have writed a project(window application) that use entity framework(code first) for data accessing.Now I want use stimulsoft for reporting . but RegData method from stimulsoft , get datatable or dataset as argumant.and I don't Know that how send data from entity framework to stimul...
11 May 2015 by Vishal Pand3y
public virtual IQueryable SqlQuery(string sqlQuery, int Id) { return Context.Database.SqlQuery(sqlQuery).AsQueryable(); }this is what I am getting from database now when I am trying to read it Like thisvar...
11 May 2015 by Grant Weatherston
I'm wanting to add a new migration in which i have removed a property of boolean 'IsRunIndividual" and added a property of int 'Type'.In theory , I would like to run the code first migration , and when I do replace all true values with '1' and false with 0.I know what you're thinking...
8 Jun 2015 by Member 10921140
I want to create an dynamic database using model classes and entity framework code first approach, without any commands. Scenario is like when admin will click on the approve button it will create an database using different connection string that I pass run-time and then database will create...
3 Aug 2015 by Member 11883599
I am new to ASP MVC and developing inventory control system. i have two main Tables(classes) Sale & SDetails as mentioned below. i want to use one single page to insert several products details and automatically calculate total. when user click issue button, all products details should be...
17 Aug 2015 by dhage.prashant01
Hi friends, I'm new to Entity Framework. In my current project, we have made use of Entity Framework: Code First ApproachCurrently we have 1 table in the DB: IncidentFollowing entity for the Incident:namespace IncidentReportingMobileService.DataObjects{ public class Incident...
15 Oct 2015 by SandeepKatakam
I have created a model and generated views using scaffolding,later i updated the model using code first migration,but must view is not updated.How to update view after model is updated?
18 Feb 2016 by RAHUL(10217975)
Hi All,I am developing MVC 4 application with Entity framework 6.0(Code First Model) on .Net framework 4.0. I was able to connect sql server using sql server authentication but I am not able to connect sql using Windows authentication.
25 Feb 2016 by je30ca
hi,I create a database by my classes in Code first Model of entity framework,I am using the Migration for update databse from classesnow How do change databse and update my classes?What I have tried:search in google and I could not find any useful link
25 Feb 2016 by Mohsin_Khan_
Please refer below linkCode-based MigrationEntity Framework Code First MigrationsCode First Migrations With Entity Framework
17 Jul 2016 by Majlesi110
i have an Entity and i want save a 2D array like below: class Location { public int Id { get; set; } public string Name { get; set; } public int[,] Locations { get; set; } } i don't know what should i do!! What I have tried:i want to...
8 Aug 2016 by Eren Yatkin
Hello, I'm trying to create views for my project. I'm using Code First approach but I dont have the Mappings. I did some research about what I need and I came across to use Entity Framework Power Tool. After this I could not get the steps about how it works.Can anyone help me ?This is...
6 Sep 2016 by njammy
I hope you will be securing these Edit user pages with Authorize attribute and other security.But to answer your question, create a FindUser page and have a set of controls which lets the editor select a user to edit.Then when the user to be edited is identified (e.g. in a grid, or...
6 Sep 2016 by OriginalGriff
We do not do your homework: it is set for a reason. It is there so that you think about what you have been told, and try to understand it. It is also there so that your tutor can identify areas where you are weak, and focus more attention on remedial action.Try it yourself, you may find it...
8 Sep 2016 by Dave Kreskowiak
Ever heard of Google, or a any search engine for that matter?You can find all this stuff yourself quite easily.
20 Sep 2016 by wa.war
public override void Up() { Sql("INSERT INTO Workouts (Id, Name, Description) VALUES (1, 'HIIT', 'High-Intensity Interval Training​')"); Sql("INSERT INTO Workouts (Id, Name, Description) VALUES (2, 'Yoga', 'Flexibility, relaxation, less stress')"); }What I have...
4 Oct 2016 by José Amílcar Casimiro
Hello,Read this articles:- A Beginner's Tutorial for Understanding Windows Communication Foundation (WCF)[^]- Walkthrough: Creating a simple WCF Service in Windows Forms[^]- WCF Tutorial[^]Google is your friend.
27 Dec 2016 by RDBurmon
This is because, you are trying to add the value in the record in incorrect orderthink, you have different order in DB and that is not matching with the parameter type which you are passing through this code
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 Peter Leow
Check this out: entity framework - Code-first vs Model/Database-first[^]
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...
7 Feb 2017 by Dishant Arora
Hi,I have two tables one is product and second is tags. They have their respective columns. There is one to many relationship between product and tags. One product can have multiple tags(This has to be done using Database, no Javascript). So, I have included Product key as foreign key into...
7 Feb 2017 by Andy Lanng
It sounds like you actually have a many to many relationship. This requires a link table which contains a foreign key for both products and tags. Each product can be inserted without constraint and each 'new' tag can be inserted without constraint. when you know which tags should be hooked up...
20 Apr 2017 by Vishal Pand3y
I'm trying to setup Unit Test in services using Moq and NUnit I tried Mocking context and DbSet like var mockSet = new Mock>(); var mockContext = new Mock(); mockContext.SetupGet(m => m.Student).Returns(mockSet.Object); but my services depends on other service...
13 Jun 2017 by Faris Karcic
Hello, so I'm junior programmer and I'm pretty much having hard time to figure this out by myself. I'm creating IoT web application based on MVC 5, with Code First database approach which does next things: - Communicate with sensors over MQTT protocol (mosquitto broker) - Shows values and some...
9 Aug 2017 by Faris Karcic
Hello guys, so I'm in creation of driver/vehicle tracking application, but I'm having issues on this part. So I'm supposed to read last record of vehicle, where data is stored which shows if vehicle is on or off (VehicleState true or false). This part is meant to show which vehicle is online...
9 Aug 2017 by Faris Karcic
In the end what I actually did was this. var online = context.VehicleUsages.Where(m => m.AccountId == userId) .GroupBy(p => p.VehicleId) .Select(p => p.FirstOrDefault(w => w.Id == p.Max(m => m.Id))) .OrderBy(p => p.VehicleOnOff) ...
15 Jan 2018 by an0ther1
The standard method of creating a many-to-many join is to create what is known as a junction table. Based on what you have provided above (Table: Event & Table: Home) you would create a third table - normally named Event__Home that consists of the following columns; a) Primary Key b) Foreign Key...
18 Feb 2018 by ahmed_sa
Problem I get error Procedure or function spAddDepartment has too many arguments specified . How to solve it . Details when insert data to table department using stored procedure spAddDepartment using fluent api in mvc5 I get error above Table department CREATE TABLE [dbo].[Departments]( ...
18 Feb 2018 by ZurdoDev
This is a very clear error message and you'll have to debug what is happening as we cannot run all your code. You are passing more than one argument to SQL and the Stored Procedure only expects 1. It may help to run SQL Profiler to see exactly what is being sent to SQL and that may help you...
22 Apr 2018 by _ProgProg_
Hello dears, I have a situation as follows: I want to alter all get queries in my application to skip deleted records which is marked as deleted in DB. Can i configure the context to exclude to do that instead of altering all queries? Regards, Amr What I have tried: i have searched a lot...
24 Apr 2018 by Gerry Schmitz
The convention is: class name + "Id". Then EF can make assumptions about an "identity" primary key. Use: [Key] public int UserId {get;set;}
24 Apr 2018 by Dave Kreskowiak
You've got this completely wrong. You don't need the Configuration class at all for such a simple relationship. I'm assuming your Room class looks something like this: public class Room { [Key] public int RoomId { get; set; } public string Name { get; set; } public string...
2 Sep 2018 by Member 13933681
i have several property in my class that after adding a new property and doing code first migration , the new added fields have null value in Previous records in database , does anybody have any idea about how to set value to them ??? What I have tried: ...
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,...
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[^]
5 Sep 2019 by Katyfanning91
I love the image hover effect style of these pictures but I want to make each picture a link to another page but when I do that using
22 Apr 2020 by Member 14789376
I'm using code first for create my database with an ASP.NET MVC project, but I didn't create index for columns. Now I want to index a few columns in my existing database, I can do it from sql server management studio. I want to ask this, should...