我正在尝试导航到与其他对象相关的对象。
在这种情况下,有2个班级; StockTakeSession 和位置。这两者具有一对一的关系。当每个类创建2个对象时,我按照下面的代码设置关系。我可以随心所欲地浏览它,没有任何问题。 但是当我从数据库中获取StockTakeSession时,只有LocationId有一个值,而Location本身为null。为了解决这个问题,我为StockTakeSession.Location创建了扩展的get方法。
我对C#/ SQLite / ORM很新,所以我想知道这是假设它是如何工作还是我需要使用不同的方法?
感谢您的任何建议。
罗伯特
这是2个类:
// These are the Stock Take Sessions
public class StockTakeSession : DomainModels
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public DateTime DateTime { get; set; }
// Navigation properties
// One to many relationship with StockItems
[OneToMany(CascadeOperations = CascadeOperation.All)]
public List<StockItem> StockItems { get; set; }
// Specify the foreign key to Location
[ForeignKey(typeof(Location))]
public int LocationId { get; set; }
// One to one relationship with Location
private Location location;
[OneToOne]
public Location Location
{
get
{
if (location == null)
{
DataBase db = new DataBase();
Location locationTemp = db.SelectLocation(LocationId);
return locationTemp;
}
else
return location;
}
set
{
location = value;
}
}
}
// These are the Locations where the Stock Take Sessions are done
public class Location : DomainModels, IComparable<Location>
{
[JsonProperty("id"), PrimaryKey]
public int Id { get; set; }
public string Name { get; set; }
public string Street { get; set; }
public int Number { get; set; }
public string Postcode { get; set; }
public string City { get; set; }
public bool Completed { get; set; }
[Ignore]
public string Label
{
get
{
return Name + " - (" + Postcode + ")";
}
}
public int CompareTo(Location other)
{
return Name.CompareTo(other.Name);
}
// Navigation property
// One to many relationship with StockItems
[OneToMany(CascadeOperations = CascadeOperation.All), Ignore]
public List<StockItem> StockItems { get; set; }
// Specify the foreign key to StockTakeSession
[ForeignKey(typeof(StockTakeSession))]
public int StockTakeSessionId { get; set; }
// One to one relationship with StockTakeSession
[OneToOne]
public StockTakeSession StockTakeSession { get; set; }
}
我如何存储对象之间的关系:
StockTakeSession newSession = new StockTakeSession
{
LocationId = selectedLocation.Id,
Location = selectedLocation,
DateTime = DateTime.Now
};
db.Insert(newSession, true);
答案 0 :(得分:2)
在sqlite-net-extensions中,不按需加载关系。您需要在需要时从数据库中获取它们。
将Location
的实施更改为简单的getter / setter。
[OneToOne]
public Location Location { get; set; }
然后,在需要时加载会话关系:
db.GetChildren(session);
例如:
db.GetWithChildren<StockTakeSession>(stockId);
将使用该Id获取StockTakeSession
对象,并加载关系并设置反向关系。