简体   繁体   中英

Entity Framework migration - issue when trying to add seed data

I'm currently building a web API with .NET for the first time; My web API holds user and trip info for a travel tracking application. I had a successful initial migration for configuring my many-to-many (trip destinations, trip members) and one-to-one (trip to do list) entities, but when I try to make data and migrate a seed...

I keep getting this error(s):

The seed entity for entity type 'TripDestination' cannot be added because it has the navigation 'Destination' set. To seed relationships, add the entity seed to 'TripDestination' and specify the foreign key values {'DestinationId'}.`

The seed entity for entity type 'ToDo' cannot be added because it has the navigation 'Trip' set. To seed relationships, add the entity seed to 'ToDo' and specify the foreign key values {'TripId'}.`

The seed entity for entity type 'TripUser' cannot be added because it has the navigation 'Trip' set. To seed relationships, add the entity seed to 'TripUser' and specify the foreign key values {'TripId'}.`

I'm not sure how to get this to work properly. Any help and input is appreciated. Here is my associated code:

Entity Models:

public class Trip
{
    [Key]
    [Required]
    public long TripId { get; set; }
    [Required]
    public string Title { get; set; } = string.Empty;
    public string Details { get; set; } = string.Empty;
    [Required]
    public DateTime StartDate { get; set; }
    [Required]
    public DateTime EndDate { get; set; }
    [Required]
    public string ImgURL { get; set; } = string.Empty;
    [Required]
    public List<TripDestination> Destinations { get; set; } = new List<TripDestination>();
    [Required]
    public List<TripUser> Members { get; set; } = new List<TripUser>();
    public List<ToDo> ToDo { get; set; } = new List<ToDo>();
}

public class ToDo
{
    public int Id { get; set; }
    public string Task { get; set; } = string.Empty;
    public bool Complete { get; set; }
    public long TripId { get; set; }
    public Trip Trip { get; set; } = new Trip();
}

public class Destination
{
    [Required]
    public string Id { get; set; } = string.Empty;
    public string City { get; set; } = string.Empty;
    public string Region { get; set; } = string.Empty;
    public string Country { get; set; } = string.Empty;
    public List<TripDestination> Trips { get; set; } = new List<TripDestination>();
}

public class User
{
    [Key]
    [Required]
    public string Username { get; set; } = string.Empty;
    [Required]
    public string Password { get; set; } = string.Empty;
    [Required]
    public string FirstName { get; set; } = string.Empty;
    [Required]
    public string LastName { get; set; } = string.Empty;
    public List<TripUser> Trips { get; set; } = new List<TripUser>();
}

public class TripDestination
{
    public long TripId { get; set; }
    public Trip Trip { get; set; } = new Trip();
    public string DestinationId { get; set; }  = string.Empty;
    public Destination Destination { get; set; } = new Destination();
}

public class TripUser
{
    public long TripId { get; set; }
    public Trip Trip { get; set; } = new Trip();
    public string Username { get; set; } = string.Empty;
    public User User { get; set; } = new User();
}

Context:

public class TravelTrackContext : DbContext
{
    public DbSet<Trip> Trips { get; set; } = null!;

    public DbSet<User> Users { get; set; } = null!;

    public TravelTrackContext(DbContextOptions<TravelTrackContext> options) : base(options)
    {

    }

    protected override void OnModelCreating(ModelBuilder bldr)
    {
        // configure TripDestination join (many-to-many)
        bldr.Entity<TripDestination>()
            .HasKey(td => new { td.TripId, td.DestinationId });

        bldr.Entity<TripDestination>()
            .HasOne(td => td.Trip)
            .WithMany(t => t.Destinations)
            .HasForeignKey(td => td.TripId);

        bldr.Entity<TripDestination>()
            .HasOne(td => td.Destination)
            .WithMany(d => d.Trips)
            .HasForeignKey(td => td.DestinationId);

        // configure TripUser join (many-to-many)
        bldr.Entity<TripUser>()
            .HasKey(d => new { d.TripId, d.Username });

        bldr.Entity<TripUser>()
            .HasOne(tu => tu.Trip)
            .WithMany(t => t.Members)
            .HasForeignKey(tu => tu.TripId);

        bldr.Entity<TripUser>()
            .HasOne(tu => tu.User)
            .WithMany(u => u.Trips)
            .HasForeignKey(tu => tu.Username);

        // configure ToDo (one-to-many)
        bldr.Entity<ToDo>()
            .HasOne(t => t.Trip)
            .WithMany(t => t.ToDo)
            .HasForeignKey(t => t.TripId)
            .OnDelete(DeleteBehavior.Cascade);

        var trips = new Trip[]
        {
            new Trip
            {
                TripId = 1,
                Title = "First Test Trip",
                Details = "Oremlay ipsumyay olorday itsay ametyay, onsectetuercay adipiscingyay elityay. Edsay itaevay eolay inyay iamday empersay orttitorpay. Ullamnay idyay augueyay. Aecenasmay atyay acuslay isquay islnay auctoryay imperdietyay. Integeryay incidunttay acinialay elitvay. Uspendissesay aretraphay. Uisday ariusvay. Ellentesquepay abitanthay orbimay istiquetray enectussay etyay etusnay etyay alesuadamay amesfay acyay urpistay egestasyay.",
                StartDate = new DateTime(2022, 3, 15),
                EndDate = new DateTime(2022, 3, 20),
                ImgURL = "assets/images/trips/img1.jpg"
            },
            new Trip
            {
                TripId = 2,
                Title = "Second Test Trip",
                Details = "Oremlay ipsumyay olorday itsay ametyay, onsectetuercay adipiscingyay elityay. Edsay itaevay eolay inyay iamday empersay orttitorpay. Ullamnay idyay augueyay. Aecenasmay atyay acuslay isquay islnay auctoryay imperdietyay. Integeryay incidunttay acinialay elitvay. Uspendissesay aretraphay. Uisday ariusvay. Ellentesquepay abitanthay orbimay istiquetray enectussay etyay etusnay etyay alesuadamay amesfay acyay urpistay egestasyay.",
                StartDate = new DateTime(2022, 5, 27),
                EndDate = new DateTime(2022, 6, 5),
                ImgURL = "assets/images/trips/img2.jpg"
            },
            new Trip
            {
                TripId = 3,
                Title = "Another Test Trip",
                Details = "",
                StartDate = new DateTime(2024, 7, 19),
                EndDate = new DateTime(2024, 8, 1),
                ImgURL = "assets/images/trips/img3.jpg"
            }
        };

        var destinations = new Destination[]
        {
            new Destination { Id = "ChIJw4OtEaZjDowRZCw_jCcczqI", City = "Zemi Beach", Region = "West End", Country = "Anguilla" },
            new Destination { Id = "ChIJASFVO5VoAIkRGJbQtRWxD7w", City = "Myrtle Beach", Region = "South Carolina", Country = "United States" },
            new Destination { Id = "ChIJdySo3EJ6_ogRa-zhruD3-jU", City = "Charleston", Region = "South Carolina", Country = "United States" },
        };

        var tripDestinations = new TripDestination[]
        {
            new TripDestination { TripId = 1, DestinationId = "ChIJw4OtEaZjDowRZCw_jCcczqI" },
            new TripDestination { TripId = 2, DestinationId = "ChIJASFVO5VoAIkRGJbQtRWxD7w" },
            new TripDestination { TripId = 2, DestinationId = "ChIJdySo3EJ6_ogRa-zhruD3-jU" },
            new TripDestination { TripId = 3, DestinationId = "ChIJdySo3EJ6_ogRa-zhruD3-jU" },
            new TripDestination { TripId = 3, DestinationId = "ChIJASFVO5VoAIkRGJbQtRWxD7w" },
        };

        var tripMembers = new TripUser[]
        {
            new TripUser { TripId = 1, Username = "user@user.com" },
            new TripUser { TripId = 1, Username = "dummyuser@dummy.dum" },
            new TripUser { TripId = 2, Username = "user@user.com" },
            new TripUser { TripId = 2, Username = "dummyuser@dummy.dum" },
            new TripUser { TripId = 2, Username = "fakeuser@fakey.fake" },
            new TripUser { TripId = 3, Username = "user@user.com" },
        };

        var toDo = new ToDo[]
        {
            new ToDo { Id = 1, TripId = 1, Task = "buy new swim trunks", Complete = true },
            new ToDo { Id = 2, TripId = 1, Task = "pack beach towels", Complete = true },
            new ToDo { Id = 3, TripId = 2, Task = "buy new swim trunks", Complete = true },
            new ToDo { Id = 4, TripId = 3, Task = "buy new swim trunks", Complete = true }
        };

        var users = new User[]
        {
            new User { Username = "user@user.com", Password = "P@ssw0rd", FirstName = "Test", LastName = "User" },
            new User { Username = "dummyuser@dummy.dum", Password = "P@ssw0rd", FirstName = "Dummy", LastName = "User" },
            new User { Username = "fakeyfake@fakey.fake", Password = "P@ssw0rd", FirstName = "Fake", LastName = "User" }
        };

        bldr.Entity<Trip>()
            .HasData(trips);

        bldr.Entity<Destination>()
            .HasData(destinations);

        bldr.Entity<TripDestination>()
            .HasData(tripDestinations);

        bldr.Entity<TripUser>()
            .HasData(tripMembers);

        bldr.Entity<ToDo>()
            .HasData(toDo);

        bldr.Entity<User>()
            .HasData(users);

        base.OnModelCreating(bldr);
    }
}

I solved the issue. It was because for my navigation properties I was initializing new instances in my entity models.

not working:

public class ToDo
{
    public int Id { get; set; }
    public string Task { get; set; } = string.Empty;
    public bool Complete { get; set; }
    public long TripId { get; set; }
    public Trip Trip { get; set; } = new Trip(); //
}
public class TripDestination {
  public long TripId { get; set; }
  public Trip Trip { get; set; } = new Trip(); //
  public string DestinationId { get; set; } = string.Empty;
  public Destination Destination { get; set; } = new Destination(); //
}
public class TripUser
{
    public long TripId { get; set; }
    public Trip Trip { get; set; } = new Trip(); //
    public string Username { get; set; } = string.Empty;
    public User User { get; set; } = new User(); //
}

working:

public class ToDo
{
    public int Id { get; set; }
    public string Task { get; set; } = string.Empty;
    public bool Complete { get; set; }
    public long TripId { get; set; }
    public Trip Trip { get; set; } = null!; //
}
public class TripDestination {
  public long TripId { get; set; }
  public Trip Trip { get; set; } = null!; //
  public string DestinationId { get; set; } = string.Empty;
  public Destination Destination { get; set; } = null!; //
}
public class TripUser
{
    public long TripId { get; set; }
    public Trip Trip { get; set; } = null!; //
    public string Username { get; set; } = string.Empty;
    public User User { get; set; } = null!; //
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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