[英]How can I add two property in my model in EF code first from one model?
I want to add two properties from the city model:我想从城市模型中添加两个属性:
after migration this error shows up:迁移后出现此错误:
Unable to determine the relationship represented by navigation 'City.Orders' of type 'ICollection'.无法确定由“ICollection”类型的导航“City.Orders”表示的关系。 Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.手动配置关系,或使用“[NotMapped]”属性或使用“OnModelCreating”中的“EntityTypeBuilder.Ignore”忽略此属性。
here is my code :这是我的代码:
public class Order
{
public virtual City FromCity { get; set; }
public virtual City ToCity { get; set; }
}
public class City
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}
I suppose your model is more complicated than just FromCity
and ToCity
because I don't think it's a good idea to store such information in a different table.我想您的模型比FromCity
和ToCity
更复杂,因为我认为将此类信息存储在不同的表中不是一个好主意。 Yet, You can use inheritance in this case.但是,您可以在这种情况下使用继承。
The table-per-hierarchy (TPH) pattern is used by default to map the inheritance in EF . table-per-hierarchy (TPH) 模式默认用于映射EF 中的继承。 TPH stores the data for all types in the hierarchy in a single table. TPH 将层次结构中所有类型的数据存储在一个表中。
However, for your scenario, you can have a base class that holds all related attributes.但是,对于您的方案,您可以拥有一个包含所有相关属性的基类。
public class CityBase
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
}
Then suppose you need two entities as per your scenario:然后假设根据您的场景需要两个实体:
public class FromCity : CityBase
{
public virtual ICollection<Order> Orders { get; set; } = null!;
}
public class ToCity : CityBase
{
public virtual ICollection<Order> Orders { get; set; } = null!;
}
And the order entity:和订单实体:
public class Order
{
public int Id { get; set; }
public string OrderTitle { get; set; } = string.Empty;
public virtual FromCity FromCity { get; set; } = null!;
public virtual ToCity ToCity { get; set; } = null!;
}
This approach can solve your problem with a One-to-Many relationship between Orders
and FromCity
, ToCity
as per below diagram:这种方法可以通过Orders
和FromCity
、 ToCity
之间的一对多关系来解决您的问题,如下图所示:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.