Reputation: 87
I am new to asp.net mvc and entity framework so I could really use some help.
I want to have new class implemented into IdentityUser class with relationship one to one. For now I have this:
public class ApplicationUser : IdentityUser
{
public virtual MapPosition MapPosition { 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;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<MapPosition> MapPositions { get; set; }
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
public class MapPosition
{
[Key, ForeignKey("ApplicationUser")]
public string UserId { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
public int PositionX { get; set; }
public int PositionY { get; set; }
}
Everything is great, new table has been created but how can I make it so everytime new user is created application also creates MapPosition entry with default values of 0 for both properties?
Upvotes: 1
Views: 1291
Reputation: 79
Consider this a workflow issue. Create the subordinate MapPosition object when it "makes-sense" in your application workflow (the place where users interact and the object now is required). These types of workflow are what MVC is all about.
User engagement is directed through an interaction on the webpage (like clicking the 'Register' a new user account link). This action is often captured in your "AccountController" as "// GET: /Account/Register". The user is directed to view the form and put required information in to register. Then on the post the server does stuff to create the ApplicationUser. You could then on the returning view, expand the workflow by:
Both of the above would require you to Create a Controller to capture this "Get", and inside that controller determine if the MapPosition is created yet, and if not initiate it. The returning View ends your workflow with something like the starting map position.
Upvotes: 0
Reputation: 12324
You could do it in the constructor:
public ApplicationUser()
{
MapPosition = new MapPosition { PositionX = 0, PositionY = 0 };
}
I prefer to construct view models in my Create action on the controller and handle it there. Then use AutoMapper to copy into the entity before updating. http://geekswithblogs.net/michelotti/archive/2009/10/25/asp.net-mvc-view-model-patterns.aspx
Upvotes: 1