Witam, mam problem ze zrozumieniem jak dodawac rekordy do baz danych po kluczu obcym. Nie wiem dlaczego, ale nie potrafie tego zrozumiec.
Mam klasy
[Table("Osoba")]
public class Osoba
{
public Osoba()
{
Adresy = new HashSet<Adresy>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int OsobaId { get; set; }
public string Imie { get; set; }
public string Nazwisko { get; set; }
public virtual ICollection<Adresy> Adresy { get; set; }
}
[Table("Adres")]
public class Adresy
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int SamochodKolorId { get; set; }
[ForeignKey("Osoba")]
public int OsobaId { get; set; }
public virtual Osoba Osoba { get; set; }
public string Adres { get; set; }
}
public class OsobaDbContext : DbContext
{
public OsobaDbContext() : base()
{
}
public DbSet<Osoba> Osoba { get; set; }
public DbSet<Adresy> Adresy { get; set; }
}
I chce dodac nowego uzytkownika wiec:
using (var context = new OsobaDbContext())
{
context.Osoba.Add(new Osoba() { Imie = "Jan", Nazwisko = "Kowalski" });
context.SaveChanges();
context.Adresy.Add(new Adresy() { Adres = "Jakis adres" });
context.SaveChanges();
}
Oczywiscie bedzie na drugim insercie exception z powodu FK. W jaki sposob mam dodac drugi rekord - w jaki sposob mam pobrac obecny id uzytkownika?
To samo tyczy sie SQLa. Na przyklad:
insert into Tabela1(kolumna1, kolumna2)
values('wartosc1','wartosc2')
/* To tej tabeli mamy klucz obcy z jedynki */
insert into Tabela2(kolumna1, kolumna2)
values((select UserId from Tabela1 where ?),'wartosc2')