entity-framework,many-to-many , Why does Entity Framework create a new entity when I try to associate an existing one?

Why does Entity Framework create a new entity when I try to associate an existing one?


Tag: entity-framework,many-to-many

I have a many-to-many relationship (Users to skills), and when I try to associate an existing skill to a user, it always creates a new one.


public class ApplicationUser : IdentityUser
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;

    public virtual ICollection<Skill> Skills { get; set; }


public class Skill
    public int Id { get; set; }

    public string Name { get; set; }


protected override void OnModelCreating(DbModelBuilder modelBuilder)

            .HasMany<Skill>(user => user.Skills)

Creating the association:

public ActionResult Skills(SkillsViewModel viewModel)
        var user = UserManager.FindById(User.Identity.GetUserId());

            && !user.Skills
            .Where(sk => sk.Name == viewModel.NewSkill)
            var foundSkill = this.db.Skills
                .Where(sk => sk.Name == viewModel.NewSkill)

            if(foundSkill != null)
                user.Skills.Add(new Skill()
                        Name = viewModel.NewSkill

        if(viewModel.SelectedSkillId > 0)
            var foundSkill = this.db.Skills.Find(viewModel.SelectedSkillId);



        return RedirectToAction("skills");

I've stepped through, and verified that I do indeed get a 'foundSkill' from the database, but after I add it to the user, and save the user, the skill associated to the user is not the one I found, but a new one with the same name and different ID.


I figured it out. The UserManager was being loaded with one DbContext, and I was trying to associate a Skill loaded from a different DbContext.

Quick hack to test and fix this was to load the user from the same DbContext as the Skills, update the user, save the DbContext.

Longer term solution would be to ensure that everything uses the same DbContext per request.


How can I verify that RemoveRange has been called on a mock DbContext?

I am using Moq to test code that calls RemoveRange on a DbSet<T>. I have mocked the context object and DbSet, but when I attempt to Verify that RemoveRange was called, I get "Expected invocation on the mock once, but was 0 times." The method I'm testing has this code:...

Unable to find the auto created Database

I have created simple ASP.NET MVC4 application using EntityFramework Code first approach. The entity class is as below: public class Album { [Key] public int AblumId { get; set; } public decimal Price { get; set; } public string Title { get; set; } } public class MusicContext : DbContext...

Sort a LINQ with another LINQ in MVC

Using SQL Server Management Using MVC VS 2013 for Web Being in a Controller Here materialnumb it's a LINQ query that always return only one value. Being the following... var materialnumb = (from r in db.MaterialNumber where r.MaterialNumber == 80254842 select r.MaterialNumber); I have another LINQ query from a...

EF Code first - many to many relation mapping table with extra columns

I am having a User Model and and a Group Model. User and Group share a many to many relationship. In when I translate this to table, I want to have a mapping table. I am using the following to achieve this. modelBuilder.Entity<UserGroup>() .HasMany(a => a.Users) .WithMany(b => b.UserGroup) .Map(mc...

Catch concurrency exception in EF6 to change message to be more user friendly

I am using EF6.1 and i would like to change the message to a more system specific message when the below exception is thrown. Store update, insert, or delete statement affected an unexpected number of rows (0) Now, my problem is i cannot seem to catch the exception? I have...

SQLite.net Extensions loads the same entity multiple times rather than returning the same reference

I'm using the PCL version of SQLite.Net Extensions in a Windows 10 universal app. This is my first time using it. It generally seems to be working, but it appears to be loading an entity multiple times rather than reusing a reference to the same object. According to the SQLite.Net...

DbSet.Attach(entity) vs DbContext.Entry(entity).State = EntityState.Modified

When I am in a detached scenario and get a dto from the client which I map into an entity to save it I do this: context.Entry(entity).State = EntityState.Modified; context.SaveChanges(); For what is then the DbSet.Attach(entity) or why should I use the .Attach method when EntityState.Modified already attaches the entity?...

how to use where with list of string

I have List Of string Like as "one" , "two" , "three" ,... I want Search From DataBase and select All Items Where have At least On of them , I wnat do this by Entity framwork , To do this I use : if (SearchVM.Tags.Count > 0) //SourceList= SourceList.Where(x=>x.Tags.Where(...));...

Why does .Where() with a Func parameter executes the query?

Here's how my DataAccessLayer works : public Foo GetFooBy(Func<Foo, bool> filter) { var query = from item in this.DataService.FooSet select item; var where = query.Where(filter); var first = where.First(); return first; } I assumed the query would be run when First() is called but it's actually executed by the Where()....

How return ID or all from another class with Entity Framework?

I learning Entity Framework, so don't blame me if this is easy for you I have class HomeNumber.cs [ScaffoldColumn(false)] [Key] public int HomeNumberId { get; set; } //[ForeignKey("HomeNumberId")] //public virtual HomeNumber HomeNumbers { get; set; } [Required(ErrorMessage = "Polje kućni broj je obavezno!")] public string HomeNumberName { get; set; }...

Foreign key not updating in entity frame work

I have a class like public class Document { [Key] public int Id { get; set; } public User ModifiedBy { get; set; } public DateTime ModifiedDate { get; set; } } Here “User” is a class with some properties (all are primitive types ) Here is my mapping of...

Managing per form ObjectContext lifetime

For ORMs like EF and NHibernate, multiple places suggest using "context per method" (or per request, per transaction) for web apps and services and using "context per form" for thick clients like WinForms and WPF. In C#, resource disposal with context per method is clean and clear with a using...

Asp.Net Identity find users not in role

I need to find all users that DONT'T contain a certain role, using Asp.Net Identity. So far I have something like this but it is not working. (From role In context.Roles From userRoles In role.Users Join us In context.Users On us.Id Equals userRoles.UserId Where role.Name <> "SomeRole" Select us.UserName) This...

Methods defined in an interface can no be used from another class

I am using Entity Framework 4.1 and code-first approach. I have the following intefaces namespace BackupCore.Contracts { public interface IEntity { DbSet getDbSet(BackupCoreContainer context); bool isNew() ; } } namespace BackupCore { interface IDao<IEntity> { IEntity Save(IEntity ent); IQueryable<IEntity> GetAll(); bool Delete(IEntity ent, out String errMsg); void SaveChanges(); } }...

EntityFramework 6 / SqlCe 4 SaveChangesAsync()

I have the following method running in a non-GUI thread within my application: private async Task PerformContextSubmitAsync() { try { await DataContextProvider.GetDefaultContext().SaveChangesAsync(); } catch (Exception ex) { Log.Error("Error performing context submit", ex); } } Which is called like this: await PerformContextSubmitAsync(); The application is a WPF/Prism based application so I'm...

Mysql Many to Many with Mapping table return one row and concatenate the values that would cause duplicate rows

I am using mysql and have three tables one for events one for officials and a mapping table between. How would I query so that the following takes place: One single row per event Concatenate the multiple values for officials into the corresponding single event row. Tables are structures as...

Select query in Entity framwork

I have two models and a dbcontext: public class User { public int UserId { get; set; } public String UserName { get; set; } public virtual ICollection<Conversation> Conversations { get; set; } } public class Conversation { public int ConversationId { get; set; } public String Text { get;...

Entity framework to CSV float values

I'm trying to write an object to csv, the thing is that my objects have float valure for exemple (14,9) i want to change them to (14.9) so it won't cause any problem with the csv format string csv = ""; using (var ctx = new NBAEntities2()) { var studentList...

EF Migrations - should an initial migration be automatically generated?

I have a project that uses EF code-first. It has automatically generated a DB from the model. Now, I want to enable EF migrations. The 'Getting Started' docs on EF Migrations suggest that in this scenario (DB already exists), two things should happen when calling Enable-Migrations: the project gets updated...

How do I mock multiple levels of DbSet.Include lambdas?

I'm using Moq to write unit tests that use Entity Framework 6 DbSet and DbContext objects. I have a service method with a cascading/multi-level Include and I can't figure out how to set it up for testing. The service method looks something like this: return DataContext.Cars .Include(p => p.Model) .Include(p...

How to map between two entities before paging

Consider the code below: public ActionResult Index(int? page) { List<ProviderViewModel> viewModel = new List<ProviderViewModel>(); List<Provider> businessModel = db.Providers .OrderBy(t => t.Name); foreach (Provider provider in businessModel) { viewModel.Add(new ProviderViewModel(provider)); } int pageSize = 9; int pageNumber = (page ?? 1); return View(viewModel.ToPagedList(pageNumber, pageSize)); } I'm using PagedList.MVC (from NuGet) and...

How to get tables from database first approach without .tt and edmx files?

I am working on database first approach. I followed the following link https://msdn.microsoft.com/en-us/data/jj200620 I'm able to get the cs files. But cs file are coming under edmx folder. but I want to get cs file directly as similar as code first approach I am using entity framework 6 and mvc...

Why does adding a parameterless constructor to my entity model class work here? What are the implications?

So I have this office entity class: [Table("office_entity")] public class EFOffice : EFBusinessEntity { [Column("address")] [StringLength(250)] public string Address { get; set; } [Column("business_name")] [StringLength(150)] public string BusinessName { get; set; } public virtual ICollection<EFEmployee> Employees { get; set; } public EFOffice(Guid id, Guid tenantId, string address, string businessName) {...

How to avoid async/await deadlock when blocking is required

I have the following issue that the SingleOrDefaultAsync from EF do not complete. I added two extra calls evaluating to a and b which both returns the correct value. But the test line is never completing and the method just waits for ever. Anyone experienced something similar or have some...

Viewmodel binding for Edit View

Having some trouble with the "GET" part of the Edit View, and can't really find anything online. So far, this is my POST section: [HttpPost] public ActionResult Edit(ContactsEditViewModel viewModel) { if (ModelState.IsValid) { var Contacts = TheContactContext.tblContacts.Find(viewModel.ID); Contacts.Company = viewModel.Company; Contacts.Contact = viewModel.Contact; Contacts.Contact2 = viewModel.Contact2; Contacts.Email1 = viewModel.Email1; Contacts.Email2...

Using SqlQuery in Entity Framework

Is this really true that order of sql parameters in sql stored procedure must match the order of sql parameters used in SqlSquery: var Parameter = new List<SqlParameter>(); Parameter.Add(new SqlParameter("@ParamOne", 1)); Parameter.Add(new SqlParameter("@ParamTwo", 2)); Parameter.Add(new SqlParameter("@ParamThree", 3)); context.Database.SqlQuery<myEntityType>("exec sp_Stored_Procedure @ParamOne, @ParamTwo, @ParamThree", Parameter.ToArray()).ToList<myEntityType>(); And in case sql developer decides to...

How to solve error in Configuration.cs in code first migration

I was setting up code first migration for model changes from Package Manager Console which creates seedmethod in Configuration.cs. i placed my code in Seed method and it shows error at context.Movies.AddorUpdate(----- it says : The type arguments for method 'System.Data.Entity.Migrations.DbSetMigrationsExtensions.AddOrUpdate(System.Data.Entity.IDbSet, params TEntity[])' cannot be inferred from the usage. Try...

How does the Take() method work in LINQ

I have a question regarding LINQ's Take() Method. I have a somewhat large table I'm querying in my web app, and I only want to return say N number of rows from the table. I've read through the MSDN documentation, but I can't see where it states if Take() first...

Entity Framework - How to get Standard Deviation using GroupBy?

I'm using entity framework 5, code first fluent API. I've built a simple query with a GroupBy for aggregation: var query = context.Table1 .GroupBy(g => new { Prop1= g.Prop1, Prop2 = g.Prop2 }) .Select(s => new { Prop1= s.Key.Prop1, Prop2= s.Key.Prop2, Avg = s.Average(m => m.Minutes), Min = s.Min(m =>...

Updating entity framework model using Linq

I have a problem with updating data in an entity framework model. I have a few tables in the model (Users, UserActivity and Orders). I have added associations between the tables, one between Users and UserActivity and one between Users and Orders. The associations are through the column UserID. These...

Entity Framework code-first: querying a view with no primary key

Our customer has given the access to views in which there is no primary key is defined. I know Entity Framework needs a primary key for table to identify. But for views not having primary key is it still possible to query. I try to find but always Entity Framework...

EF: configuring many to many relationship (code first)

In my scenario I have Jobs, Companies and Departments. Single Job may have only one Company; Company may have multiple Jobs (One-To-Many) Single Job may have multiple Departments; Department may have multiple Jobs (Many-To-Many). I want to set relations using Foreign Keys only. For that I have property of Foreign...

A specified Include path is not valid. The EntityType '*Propiedad' does not declare a navigation property with the name 'Nombre'

I am trying to implement unit of work and the generic repository pattern as explained here: http://www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application My entity Propiedad is like this: public class Propiedad { [Key] public int Id { get; set; } public virtual Entidad Entidad { get; set; } public string Codigo { get; set; }...

How to design a history for n:m relations

Problem: I have a n:m relation between a table A and another table B and it is required to have the complete history of this relation, in other words I must be able to reproduce the status of any point the past. Ideas: My first attempt is to dissect to...

Entity Framework Invalid Column (Column Does Not Exist in Database or Code)

So I have seen a lot of questions like mine. But none of the answers are working. Anytime I try to update the entity I get an Invalid Column exception: [SqlException (0x80131904): Invalid column name 'ssma$rowid'. Invalid column name 'ssma$rowid'.] Where is this coming from? I have regenerated/rebuilt/cleaned/dropped table and...

How to list objects in many to many Django

Considerer this model class Dealership(models.Model): dealership = models.CharField(max_length=50) class Ordered(models.Model): customer = models.ForeignKey("Customer") dealership = models.ManyToManyField("Dealership") status = models.CharField(max_length=2, choices=status_list, default='p') I try $ ./manage.py shell >>> from new_way.core.models import Ordered, Dealership >>> q = Ordered.objects.all()[:5] >>> [i.dealership for i in q.dealership.all] And generate error Traceback (most recent call last):...

Get a single text value using linq

I am using this line to return a value, but instead its getting a True var valor = valoresCampoAdicionalesEmpresa.Select(p => p.Key == propiedad.Nombre).First(); This the view data passes from the controller var valoresCampoAdicionalesEmpresa = (Dictionary)ViewData["ValoresCampoAdicionalesEmpresa"]; public ActionResult Edit(int? id) { var listFields = from b in db.Propiedades where b.Entidad.Nombre ==...

When are Entity instances automatically attached to a context?

I've read a few questions and texts on attachment but they seem to skip some detail on how it works. For example, I don't know why the following happens: MyContext c = new MyContext(); MyEntity e = new MyEntity(); /* some local edits in e */ c.MyEntity.Add(e); // Works fine...

How to create an input (editorfor) for a field not in the model

I have the following on my EDIT view @model Inspinia_MVC5.Areas.GlobalAdmin.Models.Empresa @{ ViewBag.Title = "Edit"; Layout = "~/Areas/GlobalAdmin/Views/Shared/_LayoutGlobalAdmin.cshtml"; var camposAdicionalesEmpresa = (List<Inspinia_MVC5.Areas.GlobalAdmin.Models.Propiedad>)ViewData["CamposAdicionalesEmpresa"]; var valoresCampoAdicionalesEmpresa = (Dictionary<string, string>)ViewData["ValoresCampoAdicionalesEmpresa"]; } and my controller is like this: public ActionResult Edit(int? id) { var listFields = from b in...

Passing conditional parameters to Database.SqlQuery

I have been doing the following to pass parameters with my sql query: var retval = context.MyObject.SqlQuery(sql.ToString(), new SqlParameter("@ProductId", productId), new SqlParameter("@CustomerId", customerId)).ToList(); I ran into a scenario where @CustomerId will not always be used in my sql string. Meaning I used an if statement to either add (Where p.CustomerId...

How to set default length on all fields in entity framework fluent api?

Is it possible to set default length of all string fields (unless I say otherwise)? At the moment it really bugs me to go and add something like modelBuilder.Entity<Game>().Property(x => x.YardLine).HasMaxLength(256); to each and every string field, just to avoid having nvarchar(max) on all my strings columns in the database....

sqlite query slow, how to optimize (using linq to entities)

I have used MS SQL server a few times and have yet to run into a speed issue when querying, using linq to entities. This time, I am using sqlite, as to ship the entire database with the application. I have a winforms app that contains 4 search fields. My...

C# entity framework MVC second run error

I am creating db and initializing data with code below, if DB doesnt exist, it creates db and populate it, when I run application second time I get error Cannot drop database "aspnet-app" because it is currently in use. Application_start, with initializations protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes);...

Avoid EF update the null image to database in .Net MVC

In my SachController, there is an Edit method like below. In the view, there are several textbox and one file-input for upload image object. Sometime, user doesn't want to change the image and they just don't select a new image. And the image (HttpPostedFileBase) is null. How can I avoid...

Related entity not loaded

I'm starting a new entity framework project and I'm defining relations among entities. I defined this simple entities: [Table("db_owner.Students")] public partial class User { [Key] public int Id { get; set; } [Required] [StringLength(50)] public string Name { get; set; } public int? SchoolClassId { get; set; } [ForeignKey("SchoolClassId")] public...

ED Code First One to Many Relationship Issue - ASP Identity

I'm configuring a database for ASP Identity and I've hit a snag. I'm looking to create a One to Many relationship between two tables, which are ApplicationUser & OrganisationUnit. An OrganisationUnit can have multiple ApplicationUsers, with an ApplicationUser only belonging to one OrganisationUnit When I add a migration and update...

Difference between cast and as inside a select in LINQ

This code throws exception: var query = services .SomeQuery(bar).select(x => (Foo)x) .Where(x.PropertyOfFoo == FooState.SomeState); var result = query.ToList(); The exception: Unable to cast the type... LINQ to Entities only supports casting EDM primitive or enumeration types. This code works: var query = services .SomeQuery(bar).select(x => x as Foo) .Where(x.PropertyOfFoo ==...

ASP.NET EF6 - 2 Tables & 1 Link Table

I am not the most fluent with ASP.NET/EF, so I am having a bit of a hard time trying to find the best way to accomplish what I need to get done. I'm trying to create a CRUD with an already existing database. Instead of the Employees table having specific...

Should i validate if related entity exists before insert?

class Customer { public int Id { get; set; } } class Sale { public int Id { get; set; } public int CustomerId { get; set; } } class SaleService { public void NewSale(Sale sale) { //Should i validate if Customer exists by sale.CustomerId before call save? saleRepository.InsertOrUpdate(sale); }...

Entity Framework: how to annotate two one-to-one relationships to same table

In a punch clock application, a given day has two foreign keys into the Punches table: PunchId_In and PunchId_Out. How can you annotate this relationship so Entity Framework creates it as intended? Note: One or both of these foreign keys may be undefined (null). public class Day { public int...