KyleK
KyleK

Reputation: 77

C# Add a column to Auto-Generated Table by Entity Framework

I'm wondering if this scenario is possible using Entity Framework.

I am using Code-First and have defined a Domain Model as follows:

public class PrintJob
{

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public int Id { get; set; }

    public virtual ICollection<StockItem> stockItemstoPrint { get; set; }

}

If I leave the above to Entity Framework and add the migration updating the database without adding the Foreign key in the StockItems Model (Which I don't want as I'd rather not have a two-way link) it will create a table for me named PrintJobStockItems which will hold PrintJobID and StockItemID
- This however is fine but I was wondering if I wanted to add a property to the PrintJobStockItems with a bool 'Printed' can it be done and have logic to update that bool value? The reason is, I want to be able to set for each individual stock item whether or not it has been printed - of course not against the stockItem Model as it should not know about PrintJobs.

If I can't achieve this, it means I will have to create a print job for every stock item, which to me isn't ideal.

Upvotes: 0

Views: 342

Answers (1)

Steve Greene
Steve Greene

Reputation: 12324

You can't access the behind the scenes join table, but the workaround is to create 2 one to manys:

public class StockItem
{
   public int Id { get; set; }  // Identity, Key is default by convention so annotation not needed
   public virtual ICollection<StockItemPrintJob> StockItemPrintJobs { get; set; }
}

public class PrintJob
{
   public int Id { get; set; }  // Identity, Key is default by convention
   public virtual ICollection<StockItemPrintJob> StockItemPrintJobs { get; set; }
}

public class StockItemPrintJob
{
   [Key, Column(Order = 0)]
   public int StockItemId { get; set; }

   [Key, Column(Order = 1)]
   public int PrintJobId { get; set; }

   public bool IsPrinted { get; set; }

   public virtual StockItem StockItem{ get; set; }
   public virtual PrintJob PrintJob { get; set; }}
}

Then you can do something like

var item = context.StockItemPrintJob.First(sp => sp.StockItemId == stockId && sp.PrintJobId == printJobId);
item.IsPrinted = true;
context.SaveChanges();

Upvotes: 1

Related Questions