我有3个继承自 OwnableSpaceObject 的类,它通过ICollections为其子级提供2个导航属性。
从 OwnableSpaceObject ,我希望能够有一个像 AddChild 这样的类,它会将一个子类添加到ICollection并将其保存到数据库中。
这是 OwnableSpaceObject 基类:
public abstract class OwnableSpaceObject : SpaceObject
{
public int? UserId { get; set; }
public int? ResourcesId { get; set; }
[ForeignKey("UserId")]
public virtual UserProfile User { get; set; }
[ForeignKey("ResourcesId")]
public virtual Resources Resources { get; set; }
public virtual ICollection<Structure> Structures { get; set; }
public virtual ICollection<Ship> Ships { get; set; }
}
以下是我尝试使用的方法:
public Structure CheckOrAddChild(StructureType _structureType)
{
using (ChronosContext db = new ChronosContext())
{
var structure = Structures != null ? Structures.FirstOrDefault(x => x.StructureTypeId == _structureType.Id) : null;
if (structure == null)
{
Structure newStructure = new Structure(_structureType.Id);
Structures.Add(newStructure); //this should add the Ship to the database and link it to the parent OwnableSpaceObject right? It errors out right here saying that Structures is null
db.SaveChanges();
structure = newStructure;
}
return structure;
}
}
类似地,一个重载的CheckOrAddChild用于添加Ships:
public virtual Ship CheckOrAddChild(ShipType _shipType)
{
using (ChronosContext db = new ChronosContext())
{
var ship = Ships != null ? Ships.FirstOrDefault(x => x.ShipTypeId == _shipType.Id) : null;
if (ship == null)
{
Ship newShip = new Ship(_shipType.Id);
Ships.Add(newShip); //this should add the Ship to the database and link it to the parent OwnableSpaceObject right? It errors out right here saying that Ships is null
db.SaveChanges();
ship = newShip;
}
return ship;
}
}
这基本上是Ships and Structures类的样子:
public class Ship
{
public int Id { get; set; }
public int CurrentAmount { get; set; }
public int BuildingAmount { get; set; }
public int ShipTypeId { get; set; }
[ForeignKey("ShipTypeId")]
public virtual ShipType ShipType { get; set; }
}
Ship / Structure类没有OwnableSpaceObject的导航属性,因为它为我的所有Fleets / Asteroids / Planets创建了一个巨大的表,因为它们都继承自OwnableSpaceObject。我想让舰队/小行星/行星在表格中分开,但仍能将船只和结构连接到它们。目前,EF在Ships / Structures表中分别命名为“Asteroid_Id”,“Planet_Id”和“Fleet_Id”3列。我应该为每个这些创建一个导航属性并自己手动链接它们吗?我试图避免这种情况,以避免重复的代码。
任何人对此都有任何想法?我在过去的两天里一直在研究,我即将神经衰弱!