如何在 Entity Framework 4 的 POCO 中定义集合?
假设我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,让我们放弃不可接受的选项。选项 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 anObjectContext
, 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.