That is the Gift class in model. That should be the parent class.
public class Gift
{
public int GiftId { get; set; }
public string Title { get; set; }
public string Brand { get; set; }
public double Price { get; set; }
public bool Chosen { get; set; }
public virtual Shop Shop { get; set; }
public virtual Person Person { get; set; }
}
That is the Shop class and these two have one to one relationship. A gift shoud have a shop, and a shop should have a gift.
public class Shop
{
public int ShopId { get; set; }
public string Name { get; set; }
public string Street { get; set; }
public string Number { get; set; }
public string Postcode { get; set; }
public string District { get; set; }
public virtual Gift Gift { get; set; }
}
That is the third class in my model. This class has one to zero relationship with the gift class. If a gift is not chosen, it does not have any person. Same for the person too.
public class Person
{
public int Id { get; set; }
public string FirstName{ get; set; }
public string Surname{ get; set; }
public string EmailAdress { get; set; }
public virtual Gift Gift { get; set; }
}
Here is the fluent api that i have lots of times changed.
modelBuilder.Entity<Gift>()
.HasOptional(x => x.Person);
modelBuilder.Entity<Person>()
.HasRequired(x => x.Gift);
modelBuilder.Entity<Gift>()
.HasRequired(x => x.Shop).WithOptional(x => x.Gift).Map(x => x.MapKey("ShopId"));
modelBuilder.Entity<Shop>()
.HasRequired(x => x.Gift).WithOptional(x => x.Shop).Map(x => x.MapKey("GiftId"));
I can save data but when i want to delete a gift, i can not succeed and have problems. How can i fix that? Thanx already!
I have fixed it. Here is the link
modelBuilder.Entity<Shop>()
.HasRequired(x => x.Gift)
.WithRequiredDependent();
modelBuilder.Entity<Gift>()
.HasRequired(x => x.Shop)
.WithRequiredPrincipal();
base.OnModelCreating(modelBuilder);