Click here to Skip to main content
15,884,975 members
Everything / Entity Framework / Entity Framework 5.0

Entity Framework 5.0

EF5.0

Great Reads

by S. M. Quamruzzaman Rahmani
ASP.NET team released Identity framework 2.0. The new release contain some new features like generic primary key. This article explain how to change primary key from string to integer & use it with MVC5.
by Dukhabandhu Sahoo
Know how to exclude types from the Model in Entity Framework Code First
by Tom Cook (UK)
How to asynchronously poll a database for an Entity with EntityFramework 5
by Dileep Ashok
Configure Many-To-Many Relationship and ListBox control in MVC and Entity Framework

Latest Articles

by Akhil Mittal
Code First Approach and Migrations in Microsoft .NET Entity Framework
by Sherjil_Ahmed
Mixing DB-First and Code First Approach for using SPs in EF-Way
by Wahid Bitar
Validated the unique constraints at dbContext ValidateEntity in a generic way by reading the IndexAttribute values.
by Nathan Minier
Generic AddOrUpdate for EF with composite key support

All Articles

Sort by Score

Entity Framework 5.0 

1 Jun 2014 by S. M. Quamruzzaman Rahmani
ASP.NET team released Identity framework 2.0. The new release contain some new features like generic primary key. This article explain how to change primary key from string to integer & use it with MVC5.
12 Oct 2014 by Dukhabandhu Sahoo
Know how to exclude types from the Model in Entity Framework Code First
30 Oct 2012 by Tom Cook (UK)
How to asynchronously poll a database for an Entity with EntityFramework 5
28 Jul 2014 by Shmuel Zang
See this CP article: LinQ Extended Joins[^].
21 Oct 2014 by vaibhavnigam383
Greetings to allI am using unit of work, repository pattern with entity framework 6 (code first approach) along with dependency injection,I have extended my repository to execute stored procedures as belowpublic List ExecuteStoreProcedure(IUnitOfWork unitofWork, string spName, params...
24 Nov 2014 by Suraj Sahoo | Coding Passion
Hello Sir,Step1- You need to build the solution once after Updating and Validating the .edmx file.Step2- Then you need to expand the .edmx file and look for the T4 template file, i.e. .tt extension file. Step3- Right click on that and Run Custom Tool. This would update the .tt file with...
24 Nov 2014 by Suraj Sahoo | Coding Passion
Quote:I don't have fixed Database Design ,i may modify existing table may add new table .As you say here, I anticipate you already have a database and may be you need modification in there in future. So I would suggest to opt for Database first approach. As you just need to add your database...
24 Nov 2014 by Sandeep Singh Shekhawat
Hi,The ADO.NET Entity Framework allows developers to choose any one approach among three possible approaches: Database First, Model First and Code First.Database First: It is a more data-centric design that is based on an existing database. The Entity Framework is able to generate a...
5 Apr 2015 by Dileep Ashok
Configure Many-To-Many Relationship and ListBox control in MVC and Entity Framework
10 Aug 2016 by Nathan Minier
Generic AddOrUpdate for EF with composite key support
14 Nov 2013 by Juan Davel
Do you absolutely need to use InProc? I suggest you either use (a) Session State Server or (b) SQL Server to manage your user sessions. I have not had one client complain about their session expiring after leaving their computer for 10-20 minutes, and we are using SQL Server to manage the user...
5 Jan 2014 by shanalikhan
Hi I have created a complete code using EF code first approach .but when i try to add controller using EF i get the following error that :unable to determine principal end of a assiciationbetween the types model.person and supplier. while in the designer the realtion ship between...
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.
16 Apr 2014 by Dave Kreskowiak
Uhhh, this may seem like a stupid response, but did you try supplying the required information it wants??It appears as though you're trying to use entity models in the place of a view model.
20 Jun 2014 by Nathan Minier
There are a number of approaches that you can take. I'm going to show the POCO route, since that's how I approach MVC.First I would make sure that the dataOffender class has a 1:M link to the charges object:public class dataOffender{ [Key,...
28 Jul 2014 by Richard Deeming
How about something like this:IDictionary result = context.A .GroupBy(a => a.AId, (AId, list) => new { AId, TrueCount = list.Count(i => i.Bit), FalseCount = list.Count(i => !i.Bit) }) .ToDictionary(x => x.AId, x => x.TrueCount -...
30 Jul 2014 by Raul Iloc
When you use entity framework an "data context" class, derived from ObjectContext is automatically created in the DataModel.Desiner.cs file. This "data context" class has 3 constructors and you should use the 2nd one, that has as parameter the connection string.So when the user change the...
20 Aug 2014 by Jameel VM
You should return the type IkkosAdminPortalWebSite.Models.RecordDetails because the view is expecting model @model IkkosAdminPortalWebSite.Models.RecordDetails but you are returning the type IkkosAdminPortalWebSite.RecordDetail in the edit controller. So before you return the type set all the...
15 Sep 2014 by Bastien Vandamme
I have a solution with 3 projects. - one for Entity framework that contains my edmx diagram (App.Config) - one for my core business (App.Config) - and one for my web API (Web.Config)When I publish my project on my hosting service or my personal server I also...
15 Oct 2014 by Suraj Sahoo | Coding Passion
Hello Ahmed,Based on your understanding, you have done a good job. I appreciate, but I would like to suggest you something here.:)First is never use Context in a controller Action Method.Try using Services where the Context method would be written i.e. the Database operations should be...
19 Oct 2014 by Suraj Sahoo | Coding Passion
check answer here[^]validation in db first[^]Please these two links, you will surely get your answer.The issue is with the model, not the view.Check and try. [HttpPost] public ActionResult Login(LoginViewModel viewModel) { if (ModelState.IsValid) ...
24 Nov 2014 by Raul Iloc
Supposing that your Entity Data Model is in a 2nd project/assembly, you have to build that project first than you can use it in you ASP.NET MVC project.
24 Nov 2014 by DamithSL
check Code-first vs Model/Database-first[^] based on the comparison you better decide which is bes for your case.
12 Dec 2014 by Nathan Minier
You're asking about two structures that do completely different things. A List is a robust collection that supports inserts as well as a few other utility functions that make it more robust than []. There is an excellent primer on enumerable types at:List vs IEnumerable vs IQueryable vs...
28 Dec 2014 by Suraj Sahoo | Coding Passion
You are out for learning a lot of things. So all the best for learning MVC. :)1- Now for your queries in the question, we cannot provide you the entire architecture for this project. But keep in mind to learn and implement the architecture so that the project is loosely coupled so that it...
16 Mar 2017 by star_tasneem
I have a database table consists of {EmployeeId,name,city,gender}. i want to retrieve them and show it in the view..but getting the exception of "Additional information: The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the...
22 Apr 2015 by Abhinav S
You can use tinyint[^] or char[^] to store 0 and 1. An alternate could also be to use a bit[^] type.Here are some examples on create a dropdownlist in a view - DropDownList / Basic usage [^]DropDownListFor with ASP.NET MVC[^]
23 Apr 2015 by Pascal Ganaye
You say "when data in that table will increase then it will consume more time"This is not necessarily as bad as you think.It really depends of the Linq provider.Let me explain.When you execute this query, the engine is not going to run it sequentially in this order: 1 -...
19 May 2015 by Raul Iloc
1.In order to add new records in the database you have to create new objects in your foreach loop.2.A 2nd problem is the fact that you are reading the same booking promo code for each item and should be read only ones before the foreach.3.A 3rd optimisation could be to save all changes...
20 May 2015 by Peter Leow
First thing first,1. There is no need for Name field in the employeestatus table as it rightfully belongs to employee table, this concerns http://www.studytonight.com/dbms/database-normalization.php[^] 2. Avoid using 'date' as field name as this is a reserved word in sql and it should be...
18 Jun 2015 by deepankarbhatnagar
Hi, try this,from f in foo join b in bar on f equals b.Id into bs from b in bs.DefaultIfEmpty() where b.Pid = 10 and b.Sid = 20 select new { Name = f.Name, Id= f.id == null ? "Null" : f.id};Thanks in advance
14 Jul 2015 by Hector Menchaca
Hello,Maybe at the moment of doing the render of your page you are not using the List class..I found this article and I think it can helps.http://stackoverflow.com/questions/27378288/but-this-dictionary-requires-a-model-item-of-type-system-collections-generic-ie[^]Best Regards!
21 Apr 2016 by Praveen_Kumar Gupta
This usually simply means a configuration issue; 1. perhaps there genuinely is no such table 2. perhaps the table is there, but isn't the the dbo scheme (it might be in Fred.Categories) 3. perhaps the db is case-sensitive (which is fine), and the table is actually...
28 Oct 2012 by Member 3212080
Hi,I am implementing Repository Pattern in one of my project based on ASP.NET MVC4 and N-Tier Architecture. I am little confused as how to implement Custom Membership with Repository Pattern. Here are how I have implemented my classes so far. For posting purpose all ...
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)...
17 Dec 2012 by Neosofty
I would like to have one model (entity framework 5), but connect to two different providers, one that supports SQL and one that supports Oracle. The idea is that I have one set of entities but with a different provider or connection string. I don't want to have two entities, one for each...
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)
4 Jan 2013 by Mninawa
Does anyone have a solution for this?Could not load type 'System.ComponentModel.DataAnnotations.DatabaseGeneratedAttribute'Could not load type 'System.ComponentModel.DataAnnotations.DatabaseGeneratedAttribute' from assembly 'EntityFramework, Version=5.0.0.0, Culture=neutral,...
7 Jan 2013 by fernando albernaz
How to do a polymorphic association like Rails using Entity Framework
27 Jan 2013 by bilalmix
hello everyone the new entity framework 5 use dbContext generator so my problem is when i use MVVM patern i need to implement INotifyPropertyChanged interfacein all my entitys and that will tak alot of time , and some ome one told me to use Object Context generator .......
20 Feb 2013 by DeepsMann
Hello,I am using EF 5.0 and Code first approach in my project.There are 10-15 tables in my database, and I have two context classes.Now, for slow start up I have read a lot of articles and blogs. I found that installing EF power tool will allow me to generate views which will help in...
8 Mar 2013 by saeed1364
hihow to create view in entity framework(ef)
8 Mar 2013 by Sandeep Mewara
You need to create Views using SQL query. Post that use it with EF. Refer: How to Use SQL Server Views with the Entity Framework[^]
8 Mar 2013 by Zoltán Zörgő
Do you really need views? With LINQ to Entities[^] you can write queries in managed code on top of the entity sets themselves (tables on the other side). The query will be transformed to actual sql query statements only when it is enumerated (this is called deferred execution). And as views are...
12 Mar 2013 by DeepsMann
Hello,I have a WCF service hosted on IIS 7.5 on my server. I have used Entity framework 5.0 in my service.When I call that service from my local system by adding service reference and creating client in a site, it takes approx 40 seconds to get the response. I tried calling the same...
12 Mar 2013 by Andy411
Some steps you can go to analyse your problem:1) Implement a simple test method in your WCF service, e.g.public in TestMethod(int data){ return (data + 1);}and look how long it takes to call it from your client.If it is fast enough, your next steps would be to see...
15 Mar 2013 by Sandeep Mewara
Your question is not too clear. Following might help:MSDN: Code First Migrations[^](HRESULT: 0x80070057 (E_INVALIDARG)) on debug [^]Clear out the temporary framework files for your project in:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\For Windows 7, the...
10 Apr 2013 by sishah10
I am using SOA architecture in my project.Client doesn't know about Entity they just know about POCO objects. As I am planning to use basic infrastructure(Service, Business Logic and Data Access Layer ) for other platforms also.Now problem I am getting is I can't maintain states of...
2 Jun 2013 by chrisndirangu
Hi I have this class;[Table("tblRegions")] public class Region : MasterEntity {public string Code { get; set; }public string Description { get; set; }public Region ParentRegion { get; set; }public Country Country { get; set; }public RegionType RegionType { get; set; } ...
19 Jun 2013 by Jitendra.Jadav
Hello,I am working on login, but WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe)is always give me false I had created the Context and this will working fine but once I try to login it always give me false result..even I had added webpages_Membership...
22 Jun 2013 by ahmed.sharu
Dear All, I want to know the best implementaion of MVC with EF5 for the next sample if we have a view like this@model...
5 Jul 2013 by Jitendra.Jadav
Hello,I have developed application in MVC 4 and EF with WCF I have created menu into _Layout page so now I am want to login with valid user so that I can authorize the access but I am not able to use Websecurity.Login it always show me false..second thing I didn't some other scenario with...
24 Jul 2013 by josh-jw
Hi All, In my application i am using database first approach with EF .so after creating entity model , i added a column to table. now i want that column in my model. hoe we can do this programatically.
25 Jul 2013 by RomilGandhi
When you are doing LogOut clear session or cookie you used. And when you LogIn check the Session,If Session is not created than users cant log to page even on clicking back button. But if you have not cleared your session properly during LogOut than it will go back
1 Aug 2013 by John-ph
Check this article, It has something "Dealing with database changes" that you are looking for in Database first approach[^]
6 Aug 2013 by moozzyk
I fixed the template a while ago so you should not see the error anymore. Btw. for 10-15 tables pre-generated views should not really make much difference unless you map tables in a very specific ways. Also, 30-40 secs is very long for such a small dataset even for the first query. Pawel
11 Oct 2013 by skipt
Hello there guysI'm using entity framework 5,is it possible, or is there a way of only detect changes in a single instance of an object rather than the all object context?what i want to do is like: Person person = new Person(); person. // make some changes...
11 Oct 2013 by Dave Kreskowiak
The first question is Why?? Since you're making a new Person object, nearly everything will be a change. The only things that won't will be the default values for your object property types, like 0 for an int.
12 Oct 2013 by skipt
Hello there and thanks for the reply.What i want to do is when i set a property on an instance, if I use "DetectChanges()" it automatically populates the navigational property and vice-versa.What is happening is that the detect changes detect that to ALL the objects loaded in the object...
17 Oct 2013 by Member 10344046
I am using MVC3 and EF5 with Oraclevar authorizedSegmentIds = _userProfile .GetSegmentListings(Permissions.OperationalControls.Edit, Permissions.OperationalControls.View, Permissions.OperationalControls.Transfer) .Select(s => s.Id)return...
29 Oct 2013 by gwyder
HiI want to map this SQL table, named Media, using EF 5.0 CodeFirst, through DataAnnotations or Fluent. [MediaID] INT NOT NULL PRIMARY KEY, [Name] VARCHAR(100) NOT NULL, [ArtistID] INT NOT NULL, [ReleaseDate] DATE NULL, [Rating] INT NULL, [Price] FLOAT...
8 Nov 2013 by Dotnet Specialist Hasnain
I have facing a problem,I have set session time out in web.config
4 Dec 2013 by Sadique KT
I have following layers in my applicaitonDate Layer (reference to Model)Business Layer(reference to Model ,Data)ModelService(WCF)-(reference to Model,Business Layer)UI (WPF/Silver Light) - Connected via WCF serviceHow do i detect the changed poco entities in an ObservableCollection...
5 Dec 2013 by Lakhan Aanjana
First tableMyidUidStart_DateLast_loginLastwall_sendLastmatch_foundScoreNamesecond TableMyidUidFidSubjectMessageStar_DateRead_messageRead_Dati want to all the message i want name from firsttable using fid whhich is uid in 1st table in...
5 Jan 2014 by Sampath Lokuge
Your declaration of models are wrong.Try is as below.public class Supplier { public int ID { get; set; } public virtual ICollection Items { get; set; } } public class Person { public int ID { get; set; } public string...
5 Jan 2014 by JoCodes
You have to set the Principal - Dependent associations using either Data Annotations or through fluent API. Means, if its 1:1 use Required annotation or 1 - 0..1 need Optional.Refer...
5 Jan 2014 by shanalikhan
Hi , Ihave one to many relatioin with section and categorycategory and subcateogryand category to item , subcategory to itemin using EF code first and setting fluent api asmodelBuilder.Entity().HasMany(p => p.Categories).WithRequired().HasForeignKey(a => a.SectionID); ...
16 Mar 2014 by mosi98
hithis is my tables class:the table roles: public partial class Role { public Role() { this.Users = new HashSet(); } public int RoleID { get; set; } public string RoleTitle { get; set; } public string...
16 Mar 2014 by Abhinav S
TryJoin Query using Entity FrameWork[^]Left Outer Join extension for Entity Framework[^]
18 Mar 2014 by mosi98
hi i upload my website to host and database(asp.net mvc4 and entity framework5),but don't know the tables and show this error: Invalid object name 'dbo.News'.Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for...
25 Mar 2014 by pykos
Hello I have a problem when updating related entities. So my Document entity has a collection of Customers. When Im adding a new document I can add as many customers as I want, but when Im updating only scalar properties are updated. This is my code for updating a document...public...
2 Apr 2014 by laxmi smiley
Enable-Migrations -ContextTypeName mvcSample.Models.Carti enabled migrations for cart.cs.migration folder with configuration is generatederror in updation.i tried Update-Database -configuration mvcSample.Models.Cartand error is:The project 'mvcSample' failed to build.please reply me
2 Apr 2014 by Code Help 2014
Check the below page for details:DataBase Update error in Entity framework.[^]
6 Apr 2014 by Gaurav Gupta A Tech Guy
how to bulk insertion in MVC 4 with EF 6 ?
15 Apr 2014 by Vishal24Anand
/// Get All Countries /// /// public IQueryable GetAllCountry() { using (Context context = new Context()) { var countries = context.COUNTRY.Select(c => new { ...
15 Apr 2014 by R-a-v-i-k-u-m-a-r
Alternative for viewbag is send the countries object as a model to view and add strogly typed view.and the code will be ,//Controller public ActionResult DisplayCountries() { DAL library = new DAL(); var country = library.GetAllCountry(); ...
16 Apr 2014 by EduChapow
There's my Model, and i can't Edit it.The errors on my ModelState returns:var errors = ModelState.Values.SelectMany(v => v.Errors);[0] - "The Field Name is Required."[1] - "The Field Id is Required."[2] - "The Field Name is Required."public class Document { ...
16 Apr 2014 by vivek painuly
how to work with entity framework code first in mvc 4 simple with example
17 Apr 2014 by niranjanmohanty
I have a project having 4 edmx files based on different module.When i have added 4 edmx files,4 connection strings generated.But i want to set a single connection string for four EDMX files.I dont want to touch the code of generated EDMX files.Is there any way to override the Entity name and...
19 Apr 2014 by Suraj Sahoo | Coding Passion
Entity Framework has been a boost to many developers.First check if the references are present for EF. Then create your classes as required for your project. Then create a controller and MVC Entityframework using CRUD(Create Read Update Delete) operation. These will give you the basic idea how...
8 May 2014 by ilaya muthumanickam
private List GetAllFieldValues(string p){ List field_values = new List(); string connectionString = ConfigurationManager.ConnectionStrings["SchoolContext"].ConnectionString; using (SqlConnection con = new SqlConnection(connectionString)) { ...
8 May 2014 by Prasad Avunoori
string colName=p;field_values = db.table1.Select(d=>new {d.colName}).Distinct().ToList();
20 May 2014 by Thang Believe
If you are using .NET 4.5 and EF 5.0, you can download the T4 Template to pre-generate views from https://ef5viewgenerator.codeplex.com/This project contains a single T4 file to add to an existing C# project hosting Entity Framework 5.0 and targeting .NET 4.5. The source code of this project...
29 May 2014 by NaveenChidara
I'm able to create mock objects and do a update test with mocked entities successfully.But the issue is with create test. Here is my sample code.In this always my testPG is null and so the test failsbase class:public class TestContext where T : class { protected Mock...
20 Jun 2014 by Vondersmith
I'm an MVC Newbie. I realize this is very basic stuff. During entry of a Master Record, how do I get my MVC Controler action to redirect to a View for a secondary file that holds multiple records linked to the master record. The scaffolding provides a view and controller to enter the...
29 Jun 2014 by Member 10226004
Hi,i written stored procedure with two select statements as belowALTER procedure [dbo].[data]@companyname nvarchar(50),@countryid int,@location nvarchar(50)asbeginselect distinct top 8 (LocationName) ,CompanyName ,Count(LocationName) as LocationCount from Job where(...
29 Jun 2014 by George Jonsson
It should be possible to use the DataAdapterDbProviderFactory factory = DbProviderFactories.GetFactory("Your database provider name");DbDataAdapter da = factory.CreateDataAdapter();DbCommand cmd = connection.CreateCommand();cmd.CommandType =...
29 Jun 2014 by Sarvesh Kumar Gupta
fetch all data into Dataset using dataadapter and sqlcommand. then bind one datalist with ds.tables[0] and 2nd with ds.Tables[1].Please use this, it will solve your problem.
11 Jul 2014 by awaisshabir
error message:'System.Web.HttpContext' does not contain a definition for 'SaveChanges' and no extension method 'SaveChanges' accepting a first argument of type 'System.Web.HttpContext' could be found (are you missing a using directive or an assembly reference?)code...
11 Jul 2014 by Gaston Verelst
Hi,In your last line you refer to Context (with uppercase) instead of context (with lowercase). These are 2 different objects.HTH,Gaston
28 Jul 2014 by kave2011
I have a table like belowBit AIdtrue 1false 1false 2true 2true 1false 3true 1false 3false 1true 2true 1true 3false 3true 2suppose corresponding entity for above table is A.I want a query entityframework method based that it subtract count of true from...
28 Jul 2014 by kave2011
I want to use left outer join for below tablesEntity1 in belowid A1 102 123 -24 105 56 37 38 5And Entity2id123456789101112Outputid A1 102 123 -24 105 56 37 ...
30 Jul 2014 by Sam k (Sam-k)
Your application attempts to delete an item but it cant pass the id for that item to delete. Try something like new{id=Model.ID} on the delete view. The ID depends on what you named yours in ur application.
3 Aug 2014 by Marcin1199
HelloI have problem. In this link:http://msdn.microsoft.com/en-us/data/gg638943[^]we can see that code is automatically generated. But when I drag and drop some entity in the same way, visual studio generate only this:using System.Windows.Documents;using...
8 Aug 2014 by Member 10964391
Hello. I'm working on MVC application and I want to save Dictionary into DB I already have (generated with EF, DB first). I've didn't manage to find solutions, apparently EF doesn't support dictionary.I will use this to associate different hashing and cryptic algorithms in my app....
8 Aug 2014 by Sergey Alexandrovich Kryukov
The concept of dictionary if very close to relational model. You just need to have a table of key-value pairs, where a dictionary key could be a primary table key. If you have to store several different dictionaries in a single table, the key uniqueness can be violated. In this case, use a...
8 Aug 2014 by Member 10964391
Thanks, this helps. But is it possible to save these function delegates as value in table?