entity-framework-core - 实体框架多对一关系 - 对象引用未设置为对象的实例
问题描述
我是实体框架的新手。我试图在两个对象之间建立关系,但这样做似乎遇到了一些问题。
我有两个实体,一个餐厅和一个支票。一个餐厅可以有多个 Check,但一个 Check 只属于一个 Restaurant。
[Table("Check")]
public class Check
{
[Key]
public Guid Id { get; set; }
public DateTime OpenDate { get; set; }
public DateTime? CloseDate { get; set; }
public decimal Amount { get; set; }
public Guid EposCheckId { get; set; }
public decimal TipAmount { get; set; }
public int TableNumber { get; set; }
public Guid StaffId { get; set; }
[ForeignKey("RestaurantId")]
public Guid RestaurantId { get; set; }
public virtual Staff memberOfStaff { get; set; }
public virtual Restaurant Restaurant { get; set; }
public virtual ICollection<Payment> Payments { get; set; }
//public ICollection<SalesEntry> SalesEntries { get; set; }
public string ToJson()
{
return JsonConvert.SerializeObject(this);
}
}
[Table("Restaurant")]
public class Restaurant
{
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
public string ContactName { get; set; }
public string Email { get; set; }
public string LoginId { get; set; }
public string Pin { get; set; }
public string EposAuthToken { get; set; }
public int EposBusinessId { get; set; }
public long EposBusinessLocationId { get; set; }
public TimeSpan DayEndTime { get; set; }
public bool Enabled { get; set; }
public string RegistrationStatus { get; set; }
public byte[] Logo { get; set; }
public string LogoContentType { get; set; }
public string UserName { get; set; }
public string PasswordHash { get; set; }
public string MerchantIdentifier { get; set; }
public string MerchantSecretKey { get; set; }
public virtual ICollection<Check> Checks { get; set; }
}
在一段代码中,我正在检索支票,然后尝试获取支票所属餐厅的 ID,但这样做会出现以下错误;
System.NullReferenceException: Object reference not set to an instance of an object.
Check 上的“Restaurant”属性似乎为空,即使 Check 上的“RestaurantId”属性可用。
我究竟做错了什么?
解决方案
推荐阅读
- python - Python多处理-在父类和衍生类之间共享的多处理数组中处理数据的问题
- python-3.x - 使用 Pymoo 重新启动优化
- apache-kafka - 使用来自 Kafka 主题的消息并将它们存储在目录 /tmp/kakfa-messages 中
- python - 由另一列 pandas df 分组的值出现的总和
- angular - 如何在 Github 上的 .NET Core 项目中部署 Angular 应用
- sql - 如何使用 invoke-sqlcmd 从 Powershell 正确格式化 XML 输出
- azure-sql-database - Azure SQL。只读副本。有没有办法管理多少副本数据库并在它们之间配置负载平衡
- html - 无论我改变什么,html中的标题图像都不会保持不变
- python - 在 Python 与 Erlang 中分析列表反转时的问题
- frameworks - 如何使用 ADO.Net 实体数据模型从存储过程“ObjectResult”创建用于 RDLC 报告的数据集