[英]How to save data in a one to zero or one relationship with Entity Framework
I have two tables that have a relationship of one to zero or one, InvoiceSale
and Budget
. 我有两个表,它们之间的关系是一比零或一, InvoiceSale
和Budget
。 A sales invoice can have a Budget
(or not), but every Budget
belongs to exactly one sales invoice. 一个销售发票可以有一个Budget
(也可以没有),但是每个Budget
都完全属于一个销售发票。
This is my InvoiceSale
class: 这是我的InvoiceSale
类别:
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: 这是我的Budget
类:
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: 这是我流利的API配置关系:
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. 当我从表单发送数据时,我发送一个下拉列表的BudgetId
值,但是当我尝试将更改保存在Entity Framework中时, BudgetId
它是一个可选字段)总是插入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. 由于我没有BudgetId
的导航属性, BudgetId
我不知道如何使用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 在InvoiceSale实体中添加Foreignkey
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,
需要在InvoiceSale表中分配值,请使用以下行BudgetId = newInvoiceSale.BudgetId,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.