ICollection.Add上的System.NullReferenceException

时间:2017-06-19 16:36:15

标签: c# sqlite xamarin error-handling

我的项目中有以下代码(Xamarin跨平台),给出错误的行是:

med.Medicine_Incident.Add(med_inc);

我不确定该行是如何引用空的,因为我们可以看到,我已将值设置为med_inc属性(时间和剂量),我也设置了med属性的值(名称和描述)。 (底部有MedicineMedicine_Incident个类)

this.BindingContext = new Medicine();

var med = (Medicine)BindingContext;

this.BindingContext = new Medicine_Incident();
var med_inc = (Medicine_Incident)BindingContext;

Medicine_Name = "Insulin";
Medicine_Desc = "Because normal digestion interferes with insulin taken by mouth, insulin must be injected";
med.Medicine_Name = Medicine_Name;
med.Medicine_Desc = Medicine_Desc;

med_inc.Dosage = Insulin_Dosage;

if (Insulin_Morning_Toggled)
{
    //Morning 8 a.m , year 2015 December 31
    Time = new DateTime(2050, 12, 31, 08, 00, 0);
    med_inc.Time = Time;

    med.Medicine_Incident.Add(med_inc);
}

Medicine上课:

public class Medicine : User_Profiles
{
    [Ignore]
    public virtual ICollection<Medicine_Incident> Medicine_Incident { get; set; }

    // This is my link to the User_Profiles PrimaryKey; A foreigh Key
    //public int User_ProfilesId { get; set; }

    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    public string Medicine_Name { get; set; }
    public string Medicine_Desc { get; set; }

    public Medicine()
    {
        Medicine_Name = "";
        Medicine_Desc = "";
    }

    public Medicine(string medicine_Name, string medicine_Desc)
    {
        Medicine_Name = medicine_Name;
        Medicine_Desc = medicine_Desc;
    }
}

Medicine_Incident上课:

public class Medicine_Incident : Medicine
{
    //[PrimaryKey, AutoIncrement]
    //public int Id { get; set; }

    // This is my link to the medicine PrimaryKey; A foreigh Key
    //public int MedicineId { get; set; }

    public DateTime Time { get; set; }
    public int Dosage { get; set; }

    public Medicine_Incident()
    {
        // (1/1/0001 12:00:00 AM)
        Time = default(DateTime);
        Dosage = 0;
    }

    public Medicine_Incident(DateTime medicine_Time, int dosage)
    {
        Time = medicine_Time;
        Dosage = dosage;
    }
}

错误可能来自[ignore]类此行中的Medicine标记:

[Ignore]
public virtual ICollection<Medicine_Incident> Medicine_Incident { get; set; }

如果是这样,那么还有另一个问题,因为我无法在没有[ignore]的情况下使用该行。如果我这样做,我会得到一个不同的错误:

  

System.NotSupportedException:不知道   System.Collections.Generic.ICollection`1 [LoginSystem.Models.Medicine]

0 个答案:

没有答案