1

I have asp.net mvc5 project, with default authentication (AccountController)

I would like to allow user to create some objects of type, lets say "MyEntity", and I would like to record it to DB. How to perform this stuff with Entity Framework Code First ?

(i.e. I want something like:

class MyEntity
{
    public Guid MyEntityId { get; set; }
    public String Name { get; set; }
    public User CreatedByUser { get; set; } // Those line I'm asking for ???
}

)

[Update]

Ok, I reached point, I needed. First:

public class MyUser : IdentityUser
{
}

Second:

public class MyDataContext : IdentityDbContext<MyUser>
{
    public MyDataContext()
        : base("MyEntitiesConnection")
    {
    }
}

Third:

public class MyEntity
{
    //....
    public MyUser User { get; set; }
}

And it's put relationship as foreign key to DB

Roman
  • 179
  • 1
  • 1
  • 10

1 Answers1

1

Just set CreatedByUser to User.Identity.Name inside your controller for the new MyEntity object. This will store the username on the model so you can query for the model. If you actually want to save a user connection then use User.Identity.Name as your parameter for the UserStore get by username and then add the user to the entity.

Casey Sebben
  • 677
  • 6
  • 14
  • Would it put relations between User and MyEntity to DB (as a foreign key) ? – Roman Nov 09 '13 at 16:19
  • 1
    Personally i'm not using relationships i'm storing the username on the other tables but if your asking about how to make the relationship then see my response to this question http://stackoverflow.com/questions/19355965/how-to-authenticate-using-mvc5rc-rtw-with-existing-database/19482896#19482896 – Casey Sebben Nov 10 '13 at 02:03