简体   繁体   English

如何配置,map EF Core中的一对一关系

[英]How to configure, map One to One Relationship in EF Core

As a student I have to design my first WebApi using.Net Core.作为一名学生,我必须使用 .Net Core 设计我的第一个 WebApi。 I have been searching for two days, and haven't found an answer that solves my problem.我一直在寻找两天,并没有找到解决我问题的答案。 Maybe because i'm a beginner.可能因为我是初学者。

I have following classes:我有以下课程:

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; }
}

I want to configure my database, so I can get a list of all the boats, with their location.我想配置我的数据库,这样我就可以获得所有船只的列表及其位置。 But I also want a list of all the locations, and if there's a boat, yes or no.但我也想要一份所有地点的清单,如果有船,是或否。

Both properties should be optional in my opinion.在我看来,这两个属性都应该是可选的。 A location doesn't necessarily own a boat, and a boat doesn't necessarily have a location.位置不一定拥有船,船也不一定有位置。

I've tried:我试过了:

Entity Framework Core zero-or-one to zero-or-one relation Entity Framework Core 零或一到零或一关系

Implementing Zero Or One to Zero Or One relationship in EF Code first by Fluent API Fluent API 首先在 EF 代码中实现零或一到零或一的关系

...but without results ...但没有结果

Edit: I would like to have a DbSet Boats that shows all my boats with their locations.编辑:我想要一个 DbSet Boats 来显示我所有的船及其位置。 And a DbSet Locations, that shows al the locations and their boats.还有一个 DbSet Locations,它显示了所有位置及其船只。

Try this:尝试这个:

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
}

and since you are using net core 5 you don't need any fluent apis并且由于您使用的是 net core 5,因此您不需要任何流利的 api

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM