如何在一个模型中首先在EF代码中添加两个属性?
我想添加城市模型中的两个属性:
迁移后,此错误显示出来:
无法确定导航代表的关系 类型“ Icollection”类型的“城市”。要么手动配置 关系,或使用“ [未图表]”忽略此属性 属性或使用“ entityTypebuilder.ignore”中的“ on ModeLcreating”。
这是我的代码:
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 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'. Either manually configure
the relationship, or ignore this property using the '[NotMapped]'
attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
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; }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想您的模型比
FromCity
和tocity
更复杂,因为我认为将这些信息存储在其他表中不是一个好主意。但是,在这种情况下,您可以使用继承。默认情况下使用table-per-hierarchy(TPH)模式来映射在EF中的继承。 TPH在单个表中将所有类型的数据存储在层次结构中。
但是,对于您的情况,您可以拥有一个持有所有相关属性的基类。
然后假设您按照您的方案需要两个实体:
订单实体:
此方法可以通过
订单
和FromCity
,之间的一对多关系来解决您的问题。代码> tocity
根据下图:I suppose your model is more complicated than just
FromCity
andToCity
because I don't think it's a good idea to store such information in a different table. Yet, You can use inheritance in this case.The table-per-hierarchy (TPH) pattern is used by default to map the inheritance in EF. TPH stores the data for all types in the hierarchy in a single table.
However, for your scenario, you can have a base class that holds all related attributes.
Then suppose you need two entities as per your scenario:
And the order entity:
This approach can solve your problem with a One-to-Many relationship between
Orders
andFromCity
,ToCity
as per below diagram: