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

MVC5: Foreign Key and data access

From Dev

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

From Dev

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

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

Foreign key mvc 4 code first c#

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

From Dev

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

From Dev

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

From Dev

Exchanged Foreign Key on Entity Framework Code First From data base

From Dev

Circular foreign key code first

From Dev

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

From Dev

How to save a foreign key in hibernate?

From Dev

How to save a foreign key in hibernate?

From Dev

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

From Dev

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

From Dev

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

From Dev

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

From Dev

Assigning UserId to Foreign Key = null

From Dev

Save/retrieve data by foreign key (API)

From Dev

Entity Framework Code First Foreign Key issue

From Dev

Disable Foreign Key Constraint Code First EF

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 with Fluent API - Code First

From Dev

Entity Framework: Foreign Key in code first

From Dev

Code first approach not creating foreign key

Related Related

  1. 1

    Code first foreign key association MVC Entity

  2. 2

    MVC5: Foreign Key and data access

  3. 3

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

  4. 4

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

  5. 5

    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

  6. 6

    Foreign key mvc 4 code first c#

  7. 7

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

  8. 8

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

  9. 9

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

  10. 10

    Exchanged Foreign Key on Entity Framework Code First From data base

  11. 11

    Circular foreign key code first

  12. 12

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

  13. 13

    How to save a foreign key in hibernate?

  14. 14

    How to save a foreign key in hibernate?

  15. 15

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

  16. 16

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

  17. 17

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

  18. 18

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

  19. 19

    Assigning UserId to Foreign Key = null

  20. 20

    Save/retrieve data by foreign key (API)

  21. 21

    Entity Framework Code First Foreign Key issue

  22. 22

    Disable Foreign Key Constraint Code First EF

  23. 23

    EF Code First Foreign Key Same Table

  24. 24

    Entity Framework Code First Foreign Key issue

  25. 25

    EF Code First foreign key with multiple keys

  26. 26

    Foreign Key in Code First Entity Framework

  27. 27

    Foreign Key with Fluent API - Code First

  28. 28

    Entity Framework: Foreign Key in code first

  29. 29

    Code first approach not creating foreign key

HotTag

Archive