如何在 Entity Framework 4 的 POCO 中定义集合?

发布于 2024-08-29 00:44:10 字数 1232 浏览 4 评论 0原文

假设我有一个 Team 类,其中包含 0 名或更多 玩家

Player 类很简单:

public class Player
{
    public long Id { get; set; }
    public string Name { get; set; }
    public Team Team { get; set; }
}

但是定义 Team 类的最佳方式是什么?

选项 1

public class Team
{
    public long Id { get; set; }
    public string Name { get; set; }
    public ICollection<Player> Players { get; set; }
}

选项 2:

public class Team
{
    public Team()
    {
        Players = new Collection<Player>();
    }

    public long Id { get; set; }
    public string Name { get; set; }
    public ICollection<Player> Players { get; set; }
}

选项 3:

public class Team
{
    public long Id { get; set; }
    public string Name { get; set; }
    public IQueryable<Player> Players { get; set; }
}

选项 4:

public class Team
{
    public long Id { get; set; }
    public string Name { get; set; }
    public ObjectSet<Player> Players { get; set; }
}

Lets say I've a Team class which contains 0 or more Players.

The Player class is easy:

public class Player
{
    public long Id { get; set; }
    public string Name { get; set; }
    public Team Team { get; set; }
}

But whats the best to define the Team class?

Option 1

public class Team
{
    public long Id { get; set; }
    public string Name { get; set; }
    public ICollection<Player> Players { get; set; }
}

Option 2:

public class Team
{
    public Team()
    {
        Players = new Collection<Player>();
    }

    public long Id { get; set; }
    public string Name { get; set; }
    public ICollection<Player> Players { get; set; }
}

Option 3:

public class Team
{
    public long Id { get; set; }
    public string Name { get; set; }
    public IQueryable<Player> Players { get; set; }
}

Option 4:

public class Team
{
    public long Id { get; set; }
    public string Name { get; set; }
    public ObjectSet<Player> Players { get; set; }
}

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

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

发布评论

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

评论(1

沫尐诺 2024-09-05 00:44:10

首先,让我们放弃不可接受的选项。选项 3 并不完全正确;我们处于对象空间,而不是 LINQ to Entities 空间。选项 4 也不正确; ObjectSet 用于 ObjectContext,而不是 POCO 类型。

剩下 1 和 2。它们都可以正常工作。如果您选择不这样做,实体框架将在从数据库具体化相关实例时初始化该集合。但是,选项 2 确实有一个优点,即您可以在自己的代码中使用新的 Team,然后再将其保存到数据库并读回。所以我可能会选择那个。

First, let's dispense with the unacceptable options. Option 3 isn't really right; we are in object space, not LINQ to Entities space. Option 4 isn't right, either; ObjectSet is for use on an ObjectContext, not on a POCO type.

That leaves 1 and 2. Both of them will work correctly. The Entity Framework will initialize the collection when materializing related instances from the database if you choose not to. However, option 2 does have the advantage that you can use a new Team in your own code before saving it to the database and reading it back. So I would probably pick that one.

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