Reputation: 2020
So I am trying to build Custom membership using EF. I dont really know what i am doing but it has gone fairly smooth so far.
I am on the Database Initializer step where i am trying to dump data into the database soon as the project runs. My class Application.cs
uses a GUID as a primary key as seen below. I am trying to figure out how i can add that GUID into the database.
I don't know if this is possible but this is what i am trying to do. I took the default login's Database you get when you make a normal web application project in VS 2012 and trying to recreate that database using EF Code First(For practice). This is what i got so far.
Class
public class Applications
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid ApplicationId { get; set; }
[StringLength(125)]
public string ApplicationName { get; set; }
}
Intializer to dump data into db on build(not including Seed.)
private static List<Applications> addApplications()
{
var apps = new List<Applications>
{
new Applications
{
ApplicationId = Guid.NewGuid(),
ApplicationName = "Test Login"
}
};
return apps;
}
private static List<Memberships> addMemberships()
{
var mem = new List<Memberships>
{
new Memberships
{
UserId = Guid.NewGuid(),
ApplicationId = ?, // How can this guid Match the one in
// in ApplicationId for the Application Table?
}
};
return mem;
}
I get "Invalid Initializer member declarator". The problem i face is that I need the GUIDS to be the same for ApplicationId
across multiple tables. I don't even know if this is possible or right?
I got a feeling I have to share it somehow maybe like
Guid AppId;
AppId = Guid.NewGuid();
Upvotes: 2
Views: 338
Reputation: 2139
In your Membership model instead of storing the GUID "ApplicationId" to try and reference the application you should use a navigation property like so (see this link for better description of navigation properties):
public class Memberships
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid UserId { get; set; }
//if you set your model up like this entity framework will take care of creating
/the foreign key for you.
public Application MemberApplication { get; set; }
}
then just pass in the appropriate application to your method like so:
private static List<Memberships> addMemberships(Application app)
{
var mem = new List<Memberships>
{
new Memberships
{
UserId = Guid.NewGuid(),
Application = app,
}
};
return mem;
}
Setting your model up like this lets you take full advantage of oop and relational database. Hope that helps.
Upvotes: 1