Sqlite在创建表时找不到类

时间:2019-03-07 02:45:46

标签: c# android sql class xamarin

我有两个班,EventScoutData

public class Event
{
    [PrimaryKey]
    public int ID
    {
        get; set;
    }

    public Event()
    {
    }
    public Event(string start, string end, string name, int id, bool isCurrent)
    {
        startDate = start;
        endDate = end;
        eventName = name;
        ID = id;
        isCurrentEvent = isCurrent;
    }

    public string startDate
    {
        get; set;
    }
    public string endDate
    {
        get; set;
    }
    public string eventName
    {
        get; set;
    }

    public bool isCurrentEvent
    {
        get; set;
    }
}

public class ScoutData
{
    [PrimaryKey]
    public int ID { get; set; }   

    public ScoutData()
    {
    }

    // Some public properties, including a public Event from the other class
}

当我尝试将表格添加到sqlite连接

public EventDatabase()
{            
    _connection = DependencyService.Get<ISQLite>().GetConnection();
    _connection.CreateTable<ScoutData>();
    _connection.CreateTable<Event>();
}

Event表生成正常,但是ScoutData表抛出此异常:

  

System.NotSupportedException:不了解App6.Event

ScoutData在其内部使用Event,但所有内容都是公共的。我尝试过重命名,清理等操作,但似乎无法弄清为什么sqlite会为某些类而不是其他类创建表。

2 个答案:

答案 0 :(得分:0)

就像杰森说的那样,如果您使用SQLite.Net Extensions,您可以这样做:

public class Event
{
    [PrimaryKey]
    public int Id { get; set; }

// Need the foreign key here
    [ForeignKey(typeof(ScoutData))]
    public int ScoutDataId { get; set; }

    public string startDate { get; set; }
    public string endDate { get; set; }
    public string eventName { get; set; }
    public bool isCurrentEvent { get; set; }

    public Event()
    {
    }

    public Event(string start, string end, string name, int id, bool isCurrent)
    {
        startDate = start;
        endDate = end;
        eventName = name;
        ID = id;
        isCurrentEvent = isCurrent;
    }
}

public class ScoutData
{
    [PrimaryKey]
    public int Id { get; set; } 

// I don't know what relationship you are looking for but this is one to one:
    [OneToOne(CascadeOperations = CascadeOperation.All)]
    public Event Event { get; set; }  

    public ScoutData()
    {
    }

    // Some public properties, including a public Event from the other class
}

如果您正在使用异步,请使用异步版本here

答案 1 :(得分:0)

我建议创建一个表ScoutDataEvent左右,以在两个表之间建立连接。

public class ScoutDataEvent
{
    [PrimaryKey]
    public int ID { get; set; }

    [NotNull]
    public int EventID { get; set; }

    [NotNull]
    public int ScoutDataID { get; set; }
}

使用此表,您可以删除ScoutData-Table中的公共事件,并使用ScoutDataID调用Event-Table。例如:

var sD = conn.Table<ScoutData>().FirstOrDefaultAsync().Result;
var sDE = conn.Table<ScoutDataEvent>().Where(p => p.ScoutDataID == sD.ID).FirstOrDefaultAsync().Result;
var event = conn.Table<Event>().Where(p => p.ID == sDE.EventID).FirstOrDefaultAsync().Result;