I have two entities:
public class Tournament
{
[Key]
public Int32 Id { get; set; }
public string Name { get; set; }
public virtual TournamentSite Site { get; set; }
}
public class TournamentSite
{
[Key]
public Int32 Id { get; set;}
public string Name { get; set; }
}
and in DbContext:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Tournament>()
.HasRequired<TournamentSite>(t => t.Site)
.WithRequiredDependent()
.Map(p => p.MapKey("IdSite"));
base.OnModelCreating(modelBuilder);
}
everything is working fine, I mean when I load a tournament it gets the TournamentSite with proper Id and Name the problem is I want to change a TournamentSite for a specific Tournament. I have tried something like this:
var tournament = dbContext.Tournaments.Find(1); // Get tournament with id 1
tournament.Site.Id = 2;
dbContext.SaveChanges();
I expect that in the Tournament table the IdSite field to be 2 now instead of 1, but whatever I do the IdSite field that is used to link Tournament to TournamentSite it’s always 1.
Any help is welcome,
Thanks.
I finally manage to do it, I have redone the models like this:
Nothing needs to be done in OnModelCreating the function looks like this:
and now I can use:
Thanks for help.