简体   繁体   English

包括抽象父EF代码优先对象的列表

[英]Include list of objects on abstract parent EF Code First

I have an abstract class named Business that looks like this: 我有一个名为Businessabstract类,如下所示:

public abstract class Business
{
  public int Id { get; set; }
  public string Name { get; set; }
  public string TaxNumber { get; set; }
  public string Description { get; set; }
  public string Phone { get; set; }
  public string Website { get; set; }
  public string Email { get; set; }
  public bool IsDeleted { get; set; }
  public virtual IEnumerable<Address> Addresses { get; set; }
  public virtual IEnumerable<Contact> Contacts { get; set; }
}

One of the classes that inherits from the above is the Supplier class. 从上面继承的类之一是Supplier类。 That looks like this: 看起来像这样:

public class Supplier : Business
{
  public virtual ICollection<PurchaseOrder> PurchaseOrders { get; set; }
}

All is good, but when I come to grab a supplier for my MVC front-end, I would like to include the Addresses associated with the Supplier. 一切都很好,但是当我为我的MVC前端争取一个供应商时,我想包括与该供应商关联的Addresses

I tried this: 我尝试了这个:

public Supplier GetSupplier(int id)
{
  return _context.Businesses.Include(b => b.Addresses).OfType<Supplier>().SingleOrDefault(x => x.Id == id);
}

But it doesn't work, it says there is no Addresses property on Supplier . 但是它不起作用,它说Supplier上没有Addresses属性。

如果将集合从IEnumerable更改为ICollection,则代码应该可以正常工作

You must implement an override since the base class is abstract. 由于基类是抽象的,因此必须实现重写。

From MSDN 从MSDN

"Members marked as abstract, or included in an abstract class, must be implemented by classes that derive from the abstract class" “标记为抽象的成员或包含在抽象类中的成员必须由从抽象类派生的类实现”

Or alternatively remove the abstract keyword so that the base is used by default. 或者,也可以删除abstract关键字,以便默认使用base。

Another alternative, remove the base and use an Interface instead unless you have a specific reason for using abstract classes. 另一个选择是,删除基并使用接口代替,除非您有使用抽象类的特殊原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM