首页 > 解决方案 > 实体框架多对一关系 - 对象引用未设置为对象的实例

问题描述

我是实体框架的新手。我试图在两个对象之间建立关系,但这样做似乎遇到了一些问题。

我有两个实体,一个餐厅和一个支票。一个餐厅可以有多个 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”属性可用。

我究竟做错了什么?

标签: entity-framework-core

解决方案


推荐阅读