实体框架导航属性的确切用途

发布于 2024-10-25 19:51:21 字数 828 浏览 1 评论 0原文

请查看以下 POCO:

public class Country
{
    [Key]
    public Guid ID { get; set; }

    [Required]
    public virtual Currency Currency { get; set; }
}

public class Currency1
{
    [Key]
    public Guid ID { get; set; }

    public virtual ICollection<Country> Countries { get; set; }
}

public class Currency2
{
    [Key]
    public Guid ID { get; set; }
}

我不太确定我需要什么导航属性,例如Currency1 中的ICollection。如果涉及 EF CodeFirst,我认为创建的数据库结构没有任何区别。在我看来,Currency1 和Currency2 的表格几乎相同。那么为什么或者什么时候添加这个额外的属性才有意义呢?

当然,只要想到 POCO,我就知道我无法从Currency2 对象访问任何国家/地区。例如:

        var a = currency1.Countries;    // works fine
        var b = currency2.Countries;    // does not even compile

但这是唯一的区别吗?换句话说:如果我不需要从Currency2对象访问国家/地区,则不需要在Currency2类中添加相应的导航属性以用于EF?这里有点困惑...

please have a look at the following POCOs:

public class Country
{
    [Key]
    public Guid ID { get; set; }

    [Required]
    public virtual Currency Currency { get; set; }
}

public class Currency1
{
    [Key]
    public Guid ID { get; set; }

    public virtual ICollection<Country> Countries { get; set; }
}

public class Currency2
{
    [Key]
    public Guid ID { get; set; }
}

I am not exactly sure what I need navigation properties like the ICollection in Currency1 for. If it comes to EF CodeFirst I see no difference in the database structure created. The tables of Currency1 and Currency2 look pretty much the same to me. So why or when does it make sense to add this extra property?

Of course, just thinking of the POCOs I understand that I can't access any countries from a Currency2 object. For example:

        var a = currency1.Countries;    // works fine
        var b = currency2.Countries;    // does not even compile

But is this the only difference? In other words: If I do not need to access countries from a Currency2 object, there is no need to add a corresponding navigation property in the Currency2 class for the purposes of EF? Kind of confused here...

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

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

发布评论

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

评论(1

晌融 2024-11-01 19:51:21

导航属性用于直接访问(如您所描述的)或用于 linq-to-entities 查询。如果您不打算使用它,可以将其从模型中删除。请注意,您需要至少一侧的导航属性,以便能够使用代码优先方法对数据库关系进行建模。

Navigation properties are used either for direct access (as you described) or in linq-to-entities queries. If you don't plan to use it you can remove it from your model. Just be aware that you need a navigation property on at least one side to be able to model database realation using the code first approach.

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