10

I'm desperate trying to create an One to Many relationship between AspNetUsers table of Identity 2.0 and a custom table called Map (One user can have many maps, but a map can only have one user) I've tryied mostly every solutions available in this website and also lost many days trying other soulutions found in the web. I'm stuck. Nothing seems to work for me. I'm new to MVC and EF so basically I think I need some sort of step-by-step guide. Can anyone please be very kind to provide me a newbie guide to achieve this from a fresh made MVC5 Project. Thanks and sorry for the redundad question I've made.

PS. I can and I'm successful on creating everykind of relationshipt between two custom tables, but not between AspNetUsers and my Map table. Thanks very very much in advance.

Malcolm T.
  • 33
  • 6
SergioPetrarca
  • 248
  • 1
  • 3
  • 13
  • i am assuming that you are using code first approach. what i will prefer is try to generate an edmx for the database and then look into the classes generated for the aspnetuser table as well, you will get the idea. first create relation to the custom table as well at db level itself – Ajay Kumar Apr 22 '15 at 10:04
  • @meajaygoel can I ask you some kind of code please? – SergioPetrarca Apr 22 '15 at 11:00
  • http://www.itorian.com/2013/11/customizing-users-profile-to-add-new.html – Ajay Kumar Apr 22 '15 at 11:07
  • have a look at his http://www.itorian.com/2013/11/customizing-users-profile-to-add-new.html – Ajay Kumar Apr 22 '15 at 11:07

3 Answers3

14

I have done exactly this on a number of projects

For instance i have a one to many relationship from ASPNetUsers to Notifications. So in my ApplicationUser class inside IdentityModels.cs i have

public virtual ICollection<Notification> Notifications { get; set; }

My Notifications class has the reverse

public virtual ApplicationUser ApplicationUser { get; set; }

By default EF will then create a cascade delete from Notification to AspNetUsers which i dont want - so i also have this in my Context class

modelBuilder.Entity<Notification>()
    .HasRequired(n => n.ApplicationUser)
    .WithMany(a => a.Notifications)
    .HasForeignKey(n => n.ApplicationUserId)
    .WillCascadeOnDelete(false);

Just remember the definition for AspNetUSers is extended in the ApplicationUser class inside IdentityModels.cs that is generated for you by visual studios scaffolding. Then treat it as any other class/table in your app

UPDATE - here are examples of full models

public class ApplicationUser : IdentityUser
{

    [StringLength(250, ErrorMessage = "About is limited to 250 characters in length.")]
    public string About { get; set; }

    [StringLength(250, ErrorMessage = "Name is limited to 250 characters in length.", MinimumLength=3)]
    public string Name { get; set; }

    public DateTime DateRegistered { get; set; }
    public string ImageUrl { get; set; }

    public virtual ICollection<Notification> Notifications { 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 Notification
{
    public int ID { get; set; }

    public int? CommentId { get; set; }

    public string ApplicationUserId { get; set; }

    public DateTime DateTime { get; set; }

    public bool Viewed { get; set; }

    public virtual ApplicationUser ApplicationUser { get; set; }

    public virtual Comment Comment { get; set; }

}

}

Symeon Breen
  • 1,531
  • 11
  • 25
  • thanks.. I think this is what I need, can you provide me a full example of your notification model and the relative code of your model's class ApplicationUser : IdentityUser, I'm trying to achieve the same, but I can't..thanks a lot! – FabioEnne May 02 '15 at 18:29
  • Thanks a lot! I will try it this week end! do I have also to enable migrations and update something? – FabioEnne May 07 '15 at 10:00
  • Yes - all of this assumes you are using code first with migrations, otherwise the changes to the model will not be reflected in the DB. HTH – Symeon Breen May 07 '15 at 10:02
  • I hope I'n not bothering you, but I'm very new..in your specific case wich fields I have to update? – FabioEnne May 07 '15 at 10:07
  • inside IdentityModels.cs public virtual ICollection Notifications { get; set; } My Notifications class has the reverse public virtual ApplicationUser ApplicationUser { get; set; } – Symeon Breen May 07 '15 at 10:08
  • I mean..in PM console wich field I have to migrate? – FabioEnne May 07 '15 at 10:10
  • ahh right - you will need to create the migrations for the applicationUser and Map objects. migrations dont just do the actual data fields, but also create indexes and foreign keys and constraints etc. – Symeon Breen May 07 '15 at 10:13
  • So basically the steps are: 1) Enable-Migrations 2) Update Map 3) Update applicationUser ? – FabioEnne May 07 '15 at 10:17
  • essentially yes. - although i am a bit worried migrations are not already enabled. - because of that when you do add-migration, it will create a migration for your entire DB. Although you can then always edit the resulting migration.cs file. – Symeon Breen May 07 '15 at 10:19
  • 3
    This worked for you? If so why did you not accepted it as an answer? I am now in the same situation as you. And you should always keep in mind that this site is a resource for future comers as well and that you should not act selfish. If it helped you, mark it as an answer.. – Subliminal Hash Aug 26 '16 at 03:59
1

Here is a step by step solution with visuals (It uses inheritance):

https://practiceaspnet.wordpress.com/2015/04/03/adding-asp-net-identity-to-an-existing-entity-framework-asp-net-web-forms-application/

renakre
  • 8,001
  • 5
  • 46
  • 99
  • Thanks very much for your help, I appriciated that, unfortunally I still can't achieve what I want.. Basically I need to create a new Db Table (Maps) whit a simple one to many relationship between AspNetUser (One AspNetUser can have many Maps). If you got time can you please provide me some code? Thanks very much – SergioPetrarca Apr 23 '15 at 10:09
0

http://www.itorian.com/2013/11/customizing-users-profile-to-add-new.html

this post contains your answer

Ajay Kumar
  • 2,031
  • 2
  • 13
  • 17
  • Thanks very much for your help, I appriciated that, unfortunally I still can't achieve what I want.. Basically I need to create a new Db Table (Maps) whit a simple one to many relationship between AspNetUser (One AspNetUser can have many Maps). If you got time can you please provide me some code? Thanks very much. – SergioPetrarca Apr 23 '15 at 10:08