微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 EF Core 中配置、映射一对一关系

如何解决如何在 EF Core 中配置、映射一对一关系

作为一名学生,我必须使用 .Net Core 设计我的第一个 WebApi。我已经搜索了两天,还没有找到解决我问题的答案。可能是因为我是初学者。

我有以下课程:

public class Boat
{
    public int BoatId { get; set; }
    public int BoatNr { get; set; }
    public string BoatName { get; set; }

    public Location Location { get; set; }
}

public class Location
{
    public int LocationId { get; set; }
    public int Row { get; set; }
    public char Side { get; set; }
    public int Level { get; set; }

    public Boat Boat { get; set; }
}

我想配置我的数据库,这样我就可以获得所有船只的列表,以及它们的位置。但我也想要一份所有地点的清单,如果有船,是或否。

在我看来,这两个属性都应该是可选的。位置不一定有船,船也不一定有位置。

我试过了:

Entity Framework Core zero-or-one to zero-or-one relation

Implementing Zero Or One to Zero Or One relationship in EF Code first by Fluent API

...但没有结果

编辑: 我想要一个 DbSet 船,显示我所有的船及其位置。还有一个 DbSet Locations,显示所有位置和他们的船。

解决方法

试试这个:

public class Boat
{
    public int Id { get; set; }

    public int BoatNr { get; set; }
    public string BoatName { get; set; }

    public int? LocationId { get; set; }
    public virtual Location Location {get; set;}
}

public class Location
{
    public int Id{ get; set; }

    public int Row { get; set; }
    public char Side { get; set; }
    public int Level { get; set; }

    public virtual ICollection<Boat> Boats { get; set; }

    //you can use this instead of collection
    public virtual Boat Boat { get; set; }
    //but I don't recommend to do this
}

并且由于您使用的是 net core 5,因此您不需要任何流畅的 api

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。