I am using EF core and CodeFirst approach to handle my database and very new to them. I created 3 model classes (IncomeTypes, AdIncomes and Students) and their relationships are as follows.
- 1:M relationship between IncomeTypes and AdIncomes
- 1:M relationship between Students and AdIncomes
My question is how should I insert data into AdIncomes table with foriegn keys (ITId and Add_No)?
My coding are as follows;
AdIncomes.cs (Complete code)
public class AdIncomes
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int AdIncomeId { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime CreateDate { get; set; }
[Required]
public decimal Amount { get; set; }
public decimal DueAmount { get; set; }
[Required]
[MaxLength(10)]
public string Status { get; set; }
}
IncomeTypes.cs
public class IncomeTypes
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ITId { get; set; }
[Required]
[Display(Name = "Income Type Name")]
[MaxLength(20)]
public string ITName { get; set; }
[Required]
...
public ICollection<AdIncomes> AdIncomes { get; set; }
}
Student.cs
public class Students
{
[Key]
[Required]
[Display(Name = "Admission No")]
[MaxLength(10)]
public string Add_No { get; set; }
[Required]
[Display(Name = "Name In Full")]
[MaxLength(150)]
public string F_Name { get; set; }
...
public ICollection<AdIncomes> AdIncomes { get; set; }
}
DbContext.cs (Complete code)
public class ConnectionString:DbContext
{
public ConnectionString(DbContextOptions<ConnectionString> options) : base(options) { }
public DbSet<AdIncomes> AdIncomes { get; set; }
public DbSet<IncomeTypes> IncomeTypes { get; set; }
public DbSet<Students> Students { get; set; }
}
AdIncomesController.cs
var incometypes2 = _context.IncomeTypes.Where(x => x.ITName.ToLower() == "admission fee").ToList();
AdIncomes AdI = new AdIncomes {
CreateDate = DateTime.Now,
DueDate = DateTime.Now.AddDays(90),
Amount = incometypes2[0].Amount,
DueAmount = incometypes2[0].Amount,
Status = "N", };
_context.Add(AdI);
await _context.SaveChangesAsync();
