0

I am trying to implement a foreign key connection between the built-in User model and my models in ASP.NET MVC 3.

How to assign ownership or some other roles to various entries represented with my models. Example of how my models look like:

public class Entry
{
    public int Id { get; set; }
    public string Value { get; set; }
    public User Owner { get; set; }
    public User SomeoneElse { get; set; }
}

Where to find the model for users, what do I need to import? Or is there a better approach to accomplish this?

gw0
  • 1,533
  • 2
  • 12
  • 13

1 Answers1

1

Do you use Entity Framework ?? If so...

Simple solution

You could simply keep the Guid from the Built-In User model. You won't have a "real relationship" but it will do the trick for what you want to do. You can always get the UserId with Membership.GetUser().ProviderUserKey

Other more complex

Completely rewrite and override the MembershipProvider and login module. That way you can use your own User object and add other properties to it aswell.

Not Sure about this one

Not sure if this one will work with the auto generated tables from the MembershipProvider but you can add the Foreign Key Property this way:

    [ForeignKey("User")]
    public Guid UserId { get; set; }
Kevin Cloet
  • 2,956
  • 1
  • 19
  • 36
  • Great! I also tried variants of the last one (also with MembershipUser), but nothing seems to work... With your hint I was also able to find similar solutions http://stackoverflow.com/questions/924692/how-do-you-get-the-userid-of-a-user-object-in-asp-net-mvc . – gw0 Jul 27 '11 at 07:07
  • Now I am wondering if the only way to create a collection of Guids is to prepare a special model only for this one-to-many relation? (Eg. so that one Entry could have multiple Owners.) – gw0 Jul 27 '11 at 07:07
  • 1
    What you want is a many to many relationship. Because the Membership User model isn't a Entity Model you will have to manually create your join/between table. So you will have to create a table that will link Entry with the UserGuid. So create a class named EntryOwners with an ID property, a Entry object and a UserGuid. Also add a Icollection in your entry object. This way Entity framework will know a Entry can have multiple EntryOwners and a EntryOwner is linked to 1 entry. – Kevin Cloet Jul 27 '11 at 07:27