Reputation: 4240
I have an ASP.NET application I created using the MVC template with Identity set to individual user accounts. That means I have a DbContext for Identity
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
And I have a local database that looks like this
I want to add a new table to my schema for credit card information. The table will be named dbo.CreditCards and will have three columns, ID int, UserName varchar(128), cardNumber char(16), expirationDate date, and CVV char(3). How can I modify this context to create that table with those columns in this schema as well?
Upvotes: 3
Views: 1840
Reputation: 23230
It is the easiest thing to do with Entity Framework. You can learn a lot by checking the Info section of EntityFramework tag here in StackOverflow. You can read the books or visit the websites listed there.
To answer your question, just create the CreditCard
entity like this:
public class CreditCard
{
public int Id { get; set; }
[StringLength(128)]
public string UserName { get; set; }
[MinLength(16), MaxLength(16)]
[Column(TypeName = "CHAR")]
public string CardNumber { get; set; }
[Column(TypeName = "DATE")]
public DateTime ExpirationDate { get; set; }
[MinLength(3), MaxLength(3)]
[Column(TypeName = "CHAR")]
public string CVV { get; set; }
}
And your DbContext
just add a new property called CreditCards
which will be of type DbSet<CreditCard>
.
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<CreditCard> CreditCards { get; set; }
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
If you recreate or update the database you'll have that table.
Upvotes: 2
Reputation: 2120
Code-first means when you want to add something, you add it to your code first.
public DbSet<CreditCardInfo> CreditCards { get; set; }
to ApplicationDbContext
Add-Migration AnyName
Update-Datebase
You can refer to this tutorial for a more detailed walkthrough.
Upvotes: 2