Click here to Skip to main content
15,901,122 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 Updated

CodeFirst 

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 ...
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..
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...
11 May 2014 by Abhinav S
Try something likeint array a; //Inputfor(int i; i
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...
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]( ...
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...
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 {...
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...
6 Sep 2016 by amir.nazarizadeh
Hi allI Implemented a edit page for asp.net identity user tableI want to pass Id to action to find the userbut I should add Id to the end of the Url to give me the viewhow can I do that?or tel me if there is better way to take the view!thanks//edit.cshtml@using...
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...
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...
16 Sep 2013 by Anh Nguyen Trong
Let try this:http://msdn.microsoft.com/en-us/library/vstudio/ee828425%28v=vs.100%29.aspx[^]http://blogs.msdn.com/b/efdesign/archive/2009/03/16/foreign-keys-in-the-entity-framework.aspx[^]
24 Aug 2017 by Anouar2002
Hello, I am using ASP MVC ENTITY FRAMEWORK CODE FIRST. I have a table called "Voiture" which contains 4 fields. I am trying now to add a new field UserID by writing this in my Class Voiture.cs : [Required] public String UserId { get; set; } but I got always this Error :
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...
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[^]
4 Sep 2019 by BillWoodruff
Consider posting on these CP forums: [^], [^] This a C# forum.
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...
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...
17 Mar 2017 by CHill60
There are several solutions available via Google. Such as this one - c# - How to call Stored Procedure in Entity Framework 6 (Code-First)? - Stack Overflow[^]
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...
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: ...
5 Apr 2014 by Dave Kreskowiak
Google for "entity framework 5 code first migrations" and you'll find what you're looking for.
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...
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.
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 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 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...
15 Jan 2018 by ddgjgj
Hi all!im working on code first database , i created my own model in Model folder and im not working with entities . I have a model class that is named Event and consists of the fields :EVENTID(STRING) DATE DESCRIPTION IMAGE . What am i trying to do now is , to create another class named Home...
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:")]...
4 Mar 2013 by dedo1991
Dear programming community,I am using code first migrations and i am trying to figure out how i can retrieve data from "Many-to-one" relationships. In other words i have a Doctor where one doctor can belong to many wards but ward can have only one doctor at a time.My objective is to...
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...
16 Sep 2013 by Dholakiya Ankit
CREATE SEQUENCE TEST_Sequence AS INT START WITH 1 INCREMENT BY 1 MINVALUE 0 NO MAXVALUE NO CACHEthis is just example i found here[^]this are othere...
28 Jul 2014 by DiponRoy
How to manage Entity Framework Code First in Real Time Projects
30 Jul 2014 by DiponRoy
How to handle database scheme changes with normal SQL scripts, without migration in Entity Framework code first
13 Aug 2014 by DiponRoy
Here, we will see how to configure one to zero/one relation between two entities in Entity Framework Code First
29 Aug 2014 by DiponRoy
Hi,have a look at this, One to zero/one relation in entity framework code first[^]
7 Aug 2022 by DiponRoy
EF Core first publishing multiple DB contexts in same DB
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...
4 Sep 2014 by Dukhabandhu Sahoo
Explore the Entity Framework Code First convention and configuration for creating primary key
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)
20 Aug 2014 by Eduard Keilholz
Have you seen this article? Seems to serve exactly your needs:Membership and Role providers for MySQL[^]
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
11 May 2014 by Emre Ataseven
int k = 10; //User input var sb = new StringBuilder(); Enumerable.Range(1, k).ToList().ForEach(p => sb.AppendLine(p + " is " + (p % 2 == 0 ? "even" : "odd"))); string result = sb.ToString();
4 Apr 2014 by Er. Puneet Goel
Just Start from this : Entity-Framework-Sample-Application-for-Beginners
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...
2 Mar 2015 by F-ES Sitecore
Store your connection string likeAccess it likestring con =...
22 Apr 2020 by F-ES Sitecore
You should add them to your code so they exist if the database is re-made from the code. Indexes - EF Core | Microsoft Docs[^] Code first, in general, is a bad idea for anything "serious". It's ok for quick prototyping or getting something...
9 Oct 2016 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.
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) ...
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...
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;}
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[^]
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; } ...
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...
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...
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...
26 May 2016 by i_syed2000
Suppose I have an existing set of database tables as following.1. Medication_Orders2. Lab_And_Radiology_Orders3. Immunization_OrdersYou can see that these tables relates to a concept of "Orders". Each table its own entity data except Lab_And_Radiology which holds two distinct type...
25 Apr 2018 by İsa KAYA
public class User { public int ID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Gender { get; set; } public string Telephone { get; set; } public string Mail { get; set; } public...
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...
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;...
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
14 Jul 2014 by johannesnestler
Hi NorouziFar,I don't see any value in asking such questions on QA. If you want to use the "Code First" Approach in EF you have to learn how the conventions and attributes work. Better go through some basic tutorial. This was first hit on goolge for me:...
24 Nov 2013 by John Korondy
It shouldn't be this hard! I am about to give up on EF...My model has weekly newspaper Editions. Each Edition can have many Classifieds. Each Classified can appear in one or more Editions. My models:public class Classifieds{ [Key,...
24 Nov 2013 by John Korondy
The problem was that EditionModel was not part of the context. Thank you, Slauma for pointing me in the right direction. The corrected Create Action is:...classifieds.Editions = new List();foreach (var p in EditionList){ var ed = await db.EditionModel.FindAsync(p); if (ed ==...
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.
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...
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
24 Oct 2016 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.
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...
31 Jul 2012 by Logan head
First part to the three part series of articles describing how to create a information system where teachers can manage there students and classes. This tutorial will go in depth on using MVC's Code First approach and touch on using MvcScaffolding in the Nuget Package Console.
22 Apr 2018 by Maciej Los
Quote: Can i configure the context to exclude to do that instead of altering all queries? No, you have to alter your queries. For further details, please see: Entity Framework Working with DbContext[^] Entity Framework Querying and Finding Entities[^]
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...
20 Aug 2014 by Manoj Kumar Choubey
I need simple membership in mvc 4 vs 2012 with mysql (Code-First Migration and Extending Identity Accounts)Please give me example of web.config and Accountcontroller I need to develop same as default template of mvc that is for sql server not for mysql
7 Oct 2016 by Manprit Singh Sahota
This article is about connecting entity framework code first approach and user defined table type function.
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...
16 Sep 2013 by Member 10197079
I am new to CodeFirst.I wish to create a Table as follows:Create Table [dbo].[UserAccount]([UserID] int Identity(1,2),[Email] nvarchar(50),[UserName] nvarchar(50),[Password]nvarchar(50),Constraint [PkUserAccount] Primary Key([UserID]),Constraint [UkEmail]...
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...
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...
11 May 2014 by Member 10810055
Using Repetition: Write a program that will prompt the user to enter a number. The program will then repeat a number of times using the number the user has entered in the first step. The program should then check each number in the loop to decide whether it is an even number or an odd...
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 Mar 2017 by Member 13002509
I don't know how to call a stored procedure so someone can help me out.....What I have tried:public class DemoEntityContext : DbContext { public DemoEntityContext() : base("DbContext") { } public DbSet Students { get; set; } public DbSet...
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 Sep 2018 by Member 13970403
I have this two errors in my code and i dont know what to do, Im totally new in this area , so if anybody can explain me itll be great. Here are my two errors. What I have tried: package android.arquitectura_mauricio_gutierrez; import android.os.Bundle; import...
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...
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)...
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...
25 Feb 2016 by Mohsin_Khan_
Please refer below linkCode-based MigrationEntity Framework Code First MigrationsCode First Migrations With Entity Framework
4 Oct 2016 by natekarsakshi
I am working on a project with MVC code first approach web app. I need to update some data daily. This is not a trigger which will update on insert or update of any data. I need to write a service which will be called daily.Need a suggestion what will be the best way to do this and how....
10 Aug 2016 by Nathan Minier
Generic AddOrUpdate for EF with composite key support
17 Jul 2016 by nilesh sawardekar
c# - How to store variable 2D array via Entity Framework? - Stack Overflow[^]Have a look at this link
16 Sep 2015 by Nils Paluch
This tip demonstrates how to use the buildin SQLite stack of Entity Framework 7 on desktop and mobile applications.
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...
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 {...