EF Code First - 多对多数据库到一对多域

发布于 2024-12-18 19:36:37 字数 541 浏览 4 评论 0原文

我希望能够拥有一个与我们当前使用的数据库模型具有不同表示形式的域模型。

目前,计划和行项目之间存在多对多关系,因此计划有许多行项目,每个行项目都可以在多个计划中重复使用。在我们的代码库中,虽然我们只需要关注特定的计划,所以场景是将现有的行项目添加到计划中或将新的行项目添加到计划中,或者获取某个行项目的集合。给定的时间表。

然而,在数据库中,我们将行项目的顺序存储在映射表上。我想要做的是将域模型中的这种关系表示为计划和行项目之间的一对多关系,并且行项目域模型具有整数顺序属性。

我似乎找不到任何方法可以使用 EF Code First 轻松展平此模型,并能够将属性放入行项目中。

本质上数据库是:

Schedule
-Id

ScheduleLineItem
-ScheduleId
-LineItemId
-Order

LineItem
-Id

我想使用的域模型是:

Schedule
-Id
-List<LineItem>

LineItem
-Id
-Order

I would like to be able to have a domain model with a different representation to the database model we are currently using.

At the moment we have a many to many relationship between a schedule and a line item, so a schedule has many line items and each line item can be reused across many schedules. In our code base though we only ever need to be concerned with a specific schedule, so the scenarios would be adding existing line items to a schedule or adding a new line item to a schedule, and alternately, getting a collection of line items for a given schedule.

In the database however we store the ordering of the line items on the mapping table. What I would like to do is represent this relationship in the doman model as a 1 to many relationship between schedule and line item and the line item domain model has an integer order property.

I can't seem to find any way to easily flatten this model using EF Code First and be able to put the property onto line item.

Essentially the database is:

Schedule
-Id

ScheduleLineItem
-ScheduleId
-LineItemId
-Order

LineItem
-Id

and the domain model I would like to use is:

Schedule
-Id
-List<LineItem>

LineItem
-Id
-Order

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

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

发布评论

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

评论(1

故人如初 2024-12-25 19:36:37

没有办法在映射中将其展平。您必须以与设计数据库相同的方式映射模型,并且可以公开模拟不存在的一对多关系的自定义非映射属性。

例如:

public class Schedule 
{
   public int Id { get; set; }
   public virtual ICollection<ScheduleLineItem> ScheduledItems { get; set; } // This is necessary for EF

   public IEnumerable<LineItem> LineItems 
   {
       return ScheduledItems.OrderBy(i => i.Order).Select(i => i.LineItem);
   }
}

There is no way to flatten it in the mapping. You must map the model in the same way as database is designed and you can expose custom non mapped properties simulating non existing one-to-many relation.

For example:

public class Schedule 
{
   public int Id { get; set; }
   public virtual ICollection<ScheduleLineItem> ScheduledItems { get; set; } // This is necessary for EF

   public IEnumerable<LineItem> LineItems 
   {
       return ScheduledItems.OrderBy(i => i.Order).Select(i => i.LineItem);
   }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文