c# Entity framework core assignment solution: Add models and tables
1. Author Class
Table Name: Authors
Properties:
AuthorId (int, primary key)
FirstName (string, required, max length 50)
LastName (string required)
BirthDate (DateTime)
Location (string)
FullName (computed property, not stored in database)
[Table("Authors")]
public class Author
{
[Key]
public int AuthorId { get; set; }
[Required]
[MaxLength(50)]
public string FirstName { get; set; }
[Required]
public string? LastName { get; set; }
public DateTime BirthDate { get; set; }
public string? Location { get; set; }
[NotMapped]
public string FullName
{
get
{
return $"{FirstName} {LastName}";
}
}
}
2. Publisher Class
Table Name: Publishers
Properties:
PublisherId (int, primary key)
Name (string, required)
Location (string)
[Table("Publishers")]
public class Publisher
{
[Key]
public int PublisherId{ get; set; }
[Required]
public string Name { get; set; }
public string? Location { get; set; }
}
3. SubCategory Class
Table Name: SubCategories
Properties:
SubCategoryId (int, primary key)
Name (string, required, max length 50)
[Table("SubCategories")]
public class SubCategory
{
[Key]
public int SubCategoryId { get; set; }
[Required]
[MaxLength(50)]
public string Name { get; set; }
}
Integrating Classes into ApplicationDBContext:
public class ApplicationDBContext:DbContext
{
public DbSet<Author> Authors { get; set; }
public DbSet<Artilcle> Articles { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Publisher> Publishers { get; set; }
public DbSet<SubCategory> SubCategories { get; set; }
override protected void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=DESKTOP-VSIUNDJ;Database=CheckEntityFrameworkCore;Trusted_Connection=True;TrustServerCertificate=true");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Category>().Property(p => p.CategoryName).HasMaxLength(50).IsUnicode(true);
modelBuilder.Entity<Artilcle>().Property(p => p.PriceForDownload).HasPrecision(10, 5);
}
}
Stay curious and keep coding!
领英推荐