I have two tables that have a relationship of one to zero or one, InvoiceSale
and Budget
. A sales invoice can have a Budget
(or not), but every Budget
belongs to exactly one sales invoice.
This is my InvoiceSale
class:
public class InvoiceSale
{
public int Id { get; set; }
public int NumberInvoice { get; set; }
public DateTime InvoiceSaleDate { get; set; }
public Budget Budget{ get; set; }
}
And this is my Budget
class:
public class Budget
{
public int Id { get; set; }
public byte StateId { get; set; }
public long Total { get; set; }
public InvoiceSale InvoiceSale { get; set; }
}
And this is my fluent API configuration of the relationship:
HasOptional(fv => fv.Budget)
.WithOptionalDependent(p => p.InvoiceSale)
.Map(m => m.MapKey("BudgetId")); //I don't have a navigation property for
//this
When I send data from a form, I send the BudgetId
value of a drop-down list, but when I try to save the changes in Entity Framework, the BudgetId
which is an optional field always inserts null.
Since I do not have a navigation property for BudgetId
, I don't know how to send this value to the database with Entity Framework.
Here is the controller action that inserts the data:
[HttpPost]
public ActionResult CreateInvoiceSale(InvoiceSale newInvoiceSale)
{
var invoiceSale = new InvoiceSale
{
NumberInvoice = newInvoiceSale.NumberInvoice ,
InvoiceSaleDate = newInvoiceSale.InvoiceSaleDate ,
// Here I need to pass the BudgetId value, but how can I do it
// without a navigation property?
};
_context.InvoiceSales.Add(invoiceSale);
_context.SaveChanges();
return Json("ok"):
}
Add Foreignkey in InvoiceSale Entity
public class InvoiceSale
{
public int Id { get; set; }
public int BudgetId { get; set; }
public int NumberInvoice { get; set; }
public DateTime InvoiceSaleDate { get; set; }
public Budget Budget { get; set; }
}
[HttpPost]
public ActionResult CreateInvoiceSale(InvoiceSale newInvoiceSale)
{
var invoiceSale = new InvoiceSale
{
BudgetId = newInvoiceSale.BudgetId,
NumberInvoice = newInvoiceSale.NumberInvoice,
InvoiceSaleDate = newInvoiceSale.InvoiceSaleDate,
//Here i need to pass the BudgetId value, but how can i do without a
//navigation property
};
_context.InvoiceSales.Add(invoiceSale);
_context.SaveChanges();
return Json("ok"):
}
Need to assign value in InvoiceSale Table, use this line BudgetId = newInvoiceSale.BudgetId,