简体   繁体   中英

Entity Framework Core - Inserting data with foreign key values

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. 1:M relationship between IncomeTypes and AdIncomes
  2. 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();

Your model design would generate the foreign key by default in database.But if you want to insert data into AdIncomes table with foreign keys.You need to add the key to your model like below:

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; }

    public int IncomeTypesITId  { get; set; }
    public IncomeTypes IncomeTypes { get; set; }
    public string StudentsAdd_No { get; set; }
    public Students Students { get; set; }
}
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; }
}
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; }
}

Controller:

//get the specific incometype
var incometypes2 = _context.IncomeTypes.Where(x => x.ITName.ToLower() == "admission fee").ToList();
//get the specific student
var student = _context.Students.Where(x => x.F_Name.ToLower() == "stu2").ToList();

AdIncomes AdI = new AdIncomes
{
    CreateDate = DateTime.Now,
    Status = "N",
    IncomeTypesITId = incometypes2[0].ITId,//add the foreign key
    StudentsAdd_No = student[0].Add_No  //add the foreign key

};
_context.Add(AdI);
await _context.SaveChangesAsync();

DbContext:

public class Mvc2_2Context : DbContext
{
    public Mvc2_2Context (DbContextOptions<Mvc2_2Context> options)
        : base(options)
    {
    }
    public DbSet<AdIncomes> AdIncomes { get; set; }
    public DbSet<IncomeTypes> IncomeTypes { get; set; }
    public DbSet<Students> Students { get; set; }
}

Result: 在此处输入图片说明

Due to you change the model.Don't forget to add-migration newMigration and update-database .

You'll need to save on object or foreign key int your AdIncome class. Entitiy Framework Core: one to many tutorial .

Here another tutorial: Entity Framework Core: one to many tutorial

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; }

    // you'll want to add your objects or foreign keys
    public Student Student { get; set; }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM