查询实体集合

发布于 2024-09-14 13:17:01 字数 232 浏览 1 评论 0原文

我已经使用默认的 EF 方式映射了我的类,并且我的所有 FK 都是 EntityCollection,因此例如 Bike.Wheels 将是 EntityCollection。

我如何使用轮子?

  • 我想检索第一个和第二个轮子
  • 我想循环遍历轮子
  • 我想获得所有轮子

。螺栓我无法使用 get/select/[]。

我错过了什么吗?

I've mapped my classes with default EF way, and all my FKs are EntityCollection, so for example Bike.Wheels would be EntityCollection.

How do I work with Wheels?

  • I want to retrieve 1st and 2nd wheel
  • I want to loop through Wheels
  • I want to get all wheel.Bolts

I could not use get/select/[].

Am I missing something?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

酸甜透明夹心 2024-09-21 13:17:01

嗯,有些操作非常简单 - 其他操作则有点笨拙 - 因此您可能需要重新设计一些方法以使用简单的方法。

要循环所有轮子,只需使用 foreach 语句:

using(BikeEntities ctx = new BikeEntities())
{
   // assuming you just somehow pick a bike to inspect the wheels for
   Bike myBike = ctx.Bikes.FirstOrDefault(b => b.BikeID == 5);

   foreach(Wheel w in myBike.Wheels)
   {
       // do something with your wheel  
       foreach(Bolt b in w.Bolts)
       {
           // do something to al the bolts on your wheel
       }           
   }
}

获取集合的第一个、第二个等有点棘手,因为您不能使用通常的数组索引。您可以:

  • 使用 .Skip() 方法 - 但这对于单个对象检索来说有点笨拙,
  • 如果集合不是太大,您可以将其“具体化”为 List; 然后使用数组索引

所以要么使用类似这样的东西:

Wheel firstWheel = myBike.Wheels.FirstOrDefault();
Wheel secondWheel = myBike.Wheels.Skip(1).FirstOrDefault();

要么将集合具体化为列表:

List<Wheel> myWheels = myBike.Wheels.ToList();

Wheel firstWheel = myWheels[0];
Wheel secondWheel = myWheels[1];

Well, some operations are really simple - others are a bit kludgy - so you might want to redesign some of your approaches to use the easy methods.

To loop over all your wheels, just use a foreach statement:

using(BikeEntities ctx = new BikeEntities())
{
   // assuming you just somehow pick a bike to inspect the wheels for
   Bike myBike = ctx.Bikes.FirstOrDefault(b => b.BikeID == 5);

   foreach(Wheel w in myBike.Wheels)
   {
       // do something with your wheel  
       foreach(Bolt b in w.Bolts)
       {
           // do something to al the bolts on your wheel
       }           
   }
}

Getting the first, second etc. of a collection is a bit more tricky, since you cannot use the usual array indexing. You can:

  • use the .Skip() method - but that's a bit clumsy for single object retrieval
  • if the collection isn't too big, you could "materialize" it into a List<T> and then use array indexing

So either you use something like this:

Wheel firstWheel = myBike.Wheels.FirstOrDefault();
Wheel secondWheel = myBike.Wheels.Skip(1).FirstOrDefault();

or you materialize the collection into a list:

List<Wheel> myWheels = myBike.Wheels.ToList();

Wheel firstWheel = myWheels[0];
Wheel secondWheel = myWheels[1];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文