I would like to insert data into TripApplicationUser table – to save that for example that Jake has enrolled for a trip to London. The table is in my SQL Server in Visual Studio. It has 2 columns: TripId and ApplicationUserId. What should I do with my databaseContext object?
public class ApplicationUser : IdentityUser
{
[PersonalData]
[Column(TypeName = "nvarchar(MAX)")]
public string FirstName { get; set; }
[PersonalData]
[Column(TypeName = "nvarchar(MAX)")]
public string Surname { get; set; }
[PersonalData]
[Column(TypeName = "nvarchar(MAX)")]
public string BirthDate { get; set; }
public ICollection<TripApplicationUser> TripApplicationUsers { get; set; }
}
public class Trip
{
public int TripId { get; set; }
public string TripDate { get; set; }
public int TripDuration { get; set; }
public int TripLength { get; set; }
public int TripSeats { get; set; }
public int TrailId { get; set; }
public Trail Trail { get; set; }
public ICollection<TripApplicationUser> TripApplicationUsers { get; set; }
}
public class TripApplicationUser
{
public int TripId { get; set; }
public Trip Trip { get; set; }
public string ApplicationUserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }
}
2
Answers
After saving ApplicationUser and Trip entities to db via EF, you can use id’s of these objects like that
1.First way:
Instantiate the relational table and configure the relationship between the other two tables in the relational table.
Demo1 as below:
Product.cs:
Supplier.cs:
MTM2Context.cs:
ProductSupplier.cs
HomeController .cs:
Result:
2.Second way:
when data do not exist in tables, add instances to context, add an instance to navigation property and call SaveChanges method from context. That is possible because Entity Framework, at the time of insert, puts primary key value (if Identity, AutoIncrement) in correspondent entity’s property inserted.
Demo 2 as below:
Product.cs:
Supplier.cs:
ProductSupplier.cs:
MtMContext.cs:
HomeController.cs:
Result: