4

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();
1
  • Quick tip for DataAnnotiations If you use Id in your class EFCore will know it's a Key. So you don't have to write [Key] manually. Commented Mar 22, 2020 at 15:24

2 Answers 2

3

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: enter image description here

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

Sign up to request clarification or add additional context in comments.

5 Comments

migratin return following error "Unable to determine the relationship represented by navigation property 'AdIncomes.students' of type 'Students'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'." "
Hi @chandrasiri,Could you update your whole model and did you change your DbContext or not?I have updated my code with the whole model and my DbContext.
please post me changes of dbContext
I have not changed your dbcontext.Did you try to remove the database and then reuse the command add-migration?
I suggest you could update the code about all of your models and the dbcontext.Maybe other model that you do not provide would make such error.Also,could you share what's the version of your project?
0

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

}

5 Comments

Do I need to change the dbContext.cs class or AdIncomes.cs class? And do I need to Update the database?
You'll need to update the database if you add field yes, you don't have to update the DbContext file because you don't add a table.
Data tables in DB already have foreign keys. But when I insert data into AdIncomes how should I add foreign key data. Are they appending automatically?
If you can see these pictures prntscr.com/rkoh0u and prntscr.com/rkoi0u
When you add the Id to the corresponding object if you do a query it will find it. So yeah now you'll just have to fille your database with id's to the objects

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.