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?

Question:

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.

User:

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; }
}

Skill:

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

    public string Name { get; set; }
}

OnModelCreating:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<ApplicationUser>()
            .HasMany<Skill>(user => user.Skills)
            .WithMany();
    }

Creating the association:

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

        if(!string.IsNullOrWhiteSpace(viewModel.NewSkill)
            && !user.Skills
            .Where(sk => sk.Name == viewModel.NewSkill)
            .Any())
        {
            var foundSkill = this.db.Skills
                .Where(sk => sk.Name == viewModel.NewSkill)
                .FirstOrDefault();

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

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


            user.Skills.Add(foundSkill);
        }

        this.UserManager.Update(user);

        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.


Answer:

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.


Related:


ASP.NET EF6 - 2 Tables & 1 Link Table


c#,sql-server,asp.net-mvc,entity-framework
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...

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


php,mysql,many-to-many,concatenation
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...

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


c#,entity-framework,unit-testing,moq
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:...

Entity Framework - How to get Standard Deviation using GroupBy?


.net,entity-framework,aggregation,standard-deviation
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 =>...

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


c#,asp.net-mvc,entity-framework,asp.net-mvc-3,razor
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...

Viewmodel binding for Edit View


c#,entity-framework,mvvm
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...

How to avoid async/await deadlock when blocking is required


entity-framework
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...

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


c#,entity-framework,entity-framework-6
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?...

Updating entity framework model using Linq


c#,sql,linq,entity-framework
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...

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


asp.net-mvc,entity-framework,null,edit,httppostedfilebase
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...

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


c#,entity-framework,generics,constructor
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) {...

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


entity-framework,entity-framework-7,sqlite-net-extensions
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...

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


c#,oracle,linq,entity-framework
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 to solve error in Configuration.cs in code first migration


c#,asp.net-mvc,entity-framework
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...

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


c#,.net,entity-framework
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...

Using SqlQuery in Entity Framework


sql-server,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...

C# entity framework MVC second run error


entity-framework,asp.net-mvc-4,localdb
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);...

Entity framework to CSV float values


c#,entity-framework,csv
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...

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


c#,asp.net-mvc,entity-framework,entity-framework-6
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...

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


c#,.net,entity-framework,ef-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....

ED Code First One to Many Relationship Issue - ASP Identity


entity-framework,ef-code-first,one-to-many
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...

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


sql,oracle,entity-framework,view,ef-code-first
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...

How does the Take() method work in LINQ


c#,.net,linq,entity-framework
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...

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


c#,asp.net,entity-framework,class
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; }...

How to list objects in many to many Django


django,many-to-many,django-queryset
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):...

Select query in Entity framwork


entity-framework
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;...

How to design a history for n:m relations


sql,plsql,many-to-many
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...

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


entity-framework,unit-testing,lambda,moq
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...

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


c#,asp.net-mvc,entity-framework,asp.net-mvc-4,repository-pattern
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; }...

Asp.Net Identity find users not in role


asp.net,linq,entity-framework,asp.net-identity
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...

Foreign key not updating in entity frame work


c#,.net,entity-framework,foreign-keys
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...

How to map between two entities before paging


c#,asp.net-mvc,entity-framework
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...

EF Migrations - should an initial migration be automatically generated?


entity-framework,code-first-migrations
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 to use where with list of string


c#,entity-framework,ef-code-first
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(...));...

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


entity-framework
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...

Unable to find the auto created Database


c#,asp.net,asp.net-mvc,entity-framework
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...

EntityFramework 6 / SqlCe 4 SaveChangesAsync()


c#,wpf,multithreading,entity-framework,sqlce
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...

Difference between cast and as inside a select in LINQ


c#,linq,entity-framework
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 ==...

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


c#,linq,entity-framework,sqlite
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...

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


c#,entity-framework,interface
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(); } }...

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


entity-framework,ef-code-first,entity-framework-6,code-first-migrations
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...

Should i validate if related entity exists before insert?


c#,entity-framework,domain-driven-design
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); }...

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


c#,asp.net,.net,entity-framework,entity-framework-6
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...

Related entity not loaded


c#,.net,entity-framework
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...

When are Entity instances automatically attached to a context?


c#,entity-framework
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...

Passing conditional parameters to Database.SqlQuery


c#,sql,linq,entity-framework
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...

EF: configuring many to many relationship (code first)


entity-framework
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...

Managing per form ObjectContext lifetime


c#,winforms,entity-framework,orm
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...

Get a single text value using linq


c#,asp.net-mvc,linq,entity-framework,asp.net-mvc-3
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 ==...

Sort a LINQ with another LINQ in MVC


sql-server,linq,entity-framework,controller
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...