我在使用EF.Core中的1to1关系时遇到了一些麻烦,
我有这些模特:
public class IncomingData
{
[Key]
[Required]
public int Id { get; set; }
...
public History History { get; set; }
}
public class History
{
[Key]
public int Id { get; set; }
...
[ForeignKey("IncomingDataId")]
public IncomingData IncomingData { get; set; }
}
历史数据库似乎正确地将ForeignKey存储为IncommingDataId
但是当我在控制器中执行以下代码时
var histories = _db.Histories.Where(x => x.IMEI == device.IMEI).OrderByDescending(x => x.Timestamp);
histories.IncomingData
始终为null
所以我必须做一些 hackish 解决方法让histories
包含IncomingData
foreach (var h in histories) {
var incomingDataRecord = _db.IncomingData.FirstOrDefault(x => x.History == h);
}
我相信我在某处做错了:)如果需要信息,我会添加
答案 0 :(得分:1)
您不包含相关的实体对象。
//Form 1
public partial class BasketScreen : Form
{
private void PurchaseButton_Click(object sender, EventArgs e)
{
// show the purchase products screen.
this.Hide();
PurchaseScreen ps = new PurchaseScreen();
ps.Show();
}
}
//UniqueNumber is the number i wish to display.
//OrderNumber is the name of the label where i want to display the UniqueNumber
//form 2
public partial class PurchaseScreen : Form
{
//private int UniqueNumber = 0; This was the issue
//This line was the fix.
private static int UniqueNumber = 0;
}
private void PurchaseScreen_Load(object sender, EventArgs e)
{
UniqueNumber++;
OrderNumber.Text = UniqueNumber.ToString("000");
}
private void BackButton_Click(object sender, EventArgs e)
{
this.Hide();
BasketScreen bs = new BasketScreen();
bs.Show();
}
答案 1 :(得分:0)
我认为History
类应该是这样的:
public class History
{
[Key]
public int Id { get; set; }
[ForeignKey(nameof(Id))]
public IncomingData IncomingData { get; set; }
}
这意味着,您使用相同的属性(Id
)来引用这两个实体。如果可以,您可以通过分配[Column]
属性为其指定不同的名称。
答案 2 :(得分:0)
没有运行它不是100%确定,但我认为你正在寻找这个...
public class IncomingData
{
[Key]
[Required]
public int Id { get; set; }
...
public History History { get; set; }
}
public class History
{
[Key]
public int Id { get; set; }
...
[InverseProperty("Id")]
public IncomingData IncomingData { get; set; }
}
然后用...
检索它var histories = _db.Histories.Where(x => x.IMEI == device.IMEI).Include("IncomingData").OrderByDescending(x => x.Timestamp);
假设IMEI和Timestamp是History
的属性