Nick Gilbert Nick Gilbert - 1 month ago 20
ASP.NET (C#) Question

Add table to Code-First ASP.NET app with Identity

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

enter image description here

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?

Answer

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.

Comments