mvc 5 code first userid as a Foreign Key - How to save data

3not3

Using MVC5 code first approach.

I haven't changed the user store, added a property called Name in ApplicationUser Class. So it looks like as follows : -

public class ApplicationUser : IdentityUser
{
    [Required]
    [StringLength(100)]
    public string Name { get; set; }

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

I have a company class, which looks like below :-

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

    [Required]
    [StringLength(255)]
    public string Name { get; set; }
}

A company will definitely has more than one user, but in my design a user can be associated with more than one company. So I have a separate class for CompanyUsers which looks as follows :-

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

    [Required]
    public virtual Company Company { get; set; }

    [Required]
    public virtual ApplicationUser User { get; set; }
}

Now, when I register a user, I'm setting its role and also companies that the user belongs to, but seems like the UserManager defined in the built-in code has already saved it. So after adding CompanyUsers data, when I call applicationDbContext.Savechanges() it fails as the user has already been saved in the database. Can you tell me how I can achieve it? I can do it in some other logic, like after creating a user, in a separate function assign users to company(s), but I want to know the solution in this circumstances. Also I can redesign the user store.

My modified register function in AccountController is as follows :-

[HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email, Name = model.Name };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await UserManager.AddToRoleAsync(user.Id, model.Role);
                var userCompany = new CompanyUsers
                {

                    Company = _context.Companies.First(t => t.Id == model.CompanyId),
                    User = user
                };

                try
                {
                    _context.CompanyUsers.Add(userCompany);
                    _context.SaveChanges();// throws exception
                }
                catch (DbEntityValidationException dbEx)
                {
                    foreach (var validationErrors in dbEx.EntityValidationErrors)
                    {
                        foreach (var validationError in validationErrors.ValidationErrors)
                        {
                            Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                        }
                    }
                }
                return RedirectToAction("UserViewAll", "Manage");
            }
            AddErrors(result);
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

I have just started mvc code first approach, so I may not understand if you use technical jargon, thanks In Advance for your help!!!!!

Daniel Bendig

Try adding the following code in the if (result.Succeeded) block:

_context.Entry(user).State = EntityState.Unchanged;

The issue appears to be that the data context in this method does not know the state of the user entity because UserManager.CreateAsync uses a separate context. The entity is attached when you assign it to the CompanyUser entity, and then this data context tries to save it as a new entity.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Code first foreign key association MVC Entity

From Dev

Disable Foreign Key Constraint Code First EF

From Dev

How to add a Foreign key in Customer table (CreatedBy column) for AspNetUser table (Id column) in ASP.NET MVC 5 Identity 2.0 using Code First

From Dev

MVC 5 Entity Framework 6 project with Database first, ViewBag, dropdown for foreign key and databinding

From Dev

Entity Framework Code First Foreign Key issue

From Dev

Circular foreign key code first

From Dev

How to save a foreign key in hibernate?

From Dev

Foreign key relationship missing in ASP.NET MVC app using code-first approach with Entity Framework

From Dev

ASP .NET C# MVC 5 Code First Foreign Key Property/Column Names

From Dev

Entity Framework - Code first - Data annotations - Unnecessary foreign key columns

From Dev

How to save a foreign key in hibernate?

From Dev

EF Code First Foreign Key Same Table

From Dev

Entity Framework Code First Foreign Key issue

From Dev

EF Code First foreign key with multiple keys

From Dev

Foreign Key in Code First Entity Framework

From Dev

Foreign key mvc 4 code first c#

From Dev

Do I need to add a foreign key Id property on mvc models code first

From Dev

Foreign Key with Fluent API - Code First

From Dev

MVC5: Foreign Key and data access

From Dev

Entity Framework: Foreign Key in code first

From Dev

Including the Foreign Key Id in Code First to save queries?

From Dev

Code first approach not creating foreign key

From Dev

Save/retrieve data by foreign key (API)

From Dev

asp.net MVC - code first foreign key lets me input anything

From Dev

How to reference foreign key which does not reference a primary key column. Asp.net mvc code first?

From Dev

How to specify a foreign key with code-first Entity Framework

From Dev

EF Code First Foreign Key Relationship

From Dev

Exchanged Foreign Key on Entity Framework Code First From data base

From Dev

I can't save a foreign key into one to many table asp.net but data can be inserted asp.net mvc 5

Related Related

  1. 1

    Code first foreign key association MVC Entity

  2. 2

    Disable Foreign Key Constraint Code First EF

  3. 3

    How to add a Foreign key in Customer table (CreatedBy column) for AspNetUser table (Id column) in ASP.NET MVC 5 Identity 2.0 using Code First

  4. 4

    MVC 5 Entity Framework 6 project with Database first, ViewBag, dropdown for foreign key and databinding

  5. 5

    Entity Framework Code First Foreign Key issue

  6. 6

    Circular foreign key code first

  7. 7

    How to save a foreign key in hibernate?

  8. 8

    Foreign key relationship missing in ASP.NET MVC app using code-first approach with Entity Framework

  9. 9

    ASP .NET C# MVC 5 Code First Foreign Key Property/Column Names

  10. 10

    Entity Framework - Code first - Data annotations - Unnecessary foreign key columns

  11. 11

    How to save a foreign key in hibernate?

  12. 12

    EF Code First Foreign Key Same Table

  13. 13

    Entity Framework Code First Foreign Key issue

  14. 14

    EF Code First foreign key with multiple keys

  15. 15

    Foreign Key in Code First Entity Framework

  16. 16

    Foreign key mvc 4 code first c#

  17. 17

    Do I need to add a foreign key Id property on mvc models code first

  18. 18

    Foreign Key with Fluent API - Code First

  19. 19

    MVC5: Foreign Key and data access

  20. 20

    Entity Framework: Foreign Key in code first

  21. 21

    Including the Foreign Key Id in Code First to save queries?

  22. 22

    Code first approach not creating foreign key

  23. 23

    Save/retrieve data by foreign key (API)

  24. 24

    asp.net MVC - code first foreign key lets me input anything

  25. 25

    How to reference foreign key which does not reference a primary key column. Asp.net mvc code first?

  26. 26

    How to specify a foreign key with code-first Entity Framework

  27. 27

    EF Code First Foreign Key Relationship

  28. 28

    Exchanged Foreign Key on Entity Framework Code First From data base

  29. 29

    I can't save a foreign key into one to many table asp.net but data can be inserted asp.net mvc 5

HotTag

Archive