-1

As a student I have to design my first WebApi using .Net Core. 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

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

...but without results

Edit: I would like to have a DbSet Boats that shows all my boats with their locations. And a DbSet Locations, that shows al the locations and their boats.

Segher
  • 3
  • 2
  • 1
    So what does or doesn't this code do? Can you show your configuration and the code that accesses the database, and explain what you expect to happen and what actually happens? – CodeCaster Mar 09 '21 at 13:05

1 Answers1

1

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

Serge
  • 40,935
  • 4
  • 18
  • 45