我有 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 和 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 表中创建了 3 个列,分别命名为“Asteroid_Id”、“Planet_Id”和“Fleet_Id”。我应该为每一个创建一个导航属性并自己手动链接它们吗?我试图避免这种情况以避免重复代码。
有人对此有任何想法吗?这两天我一直在研究,我快要精神崩溃了!