I have two tables that i want to join Game and Details. Game has one Detail
The problem is that i cant bind the tables correct. The error i get is
"The entity types 'Game' and 'Details' cannot share table 'Details' because they are not in the same type hierarchy or do not have a valid one to one foreign key relationship with matching primary keys between them."
Here is my implementation
public class Game
{
[Key]
[ForeignKey("GameDetails")]
public int GameId { get; set; }
public string GameName { get; set; }
//Navigation prop
public virtual Details GameDetails { get; set; }
public virtual ICollection<Details> DetailsId { get; set; }
}
public class Details
{
[Key]
public int DetailsId { get; set; }
public int GameId { get; set; }
public int RatingId { get; set; }
public int Grade { get; set; }
//Navigation prop
[ForeignKey("DetailsId")]
public virtual Game GameDetails { get; set; }
public virtual RatingCompany RatingCompany { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Game>().HasKey(f => f.GameId);
modelBuilder.Entity<Game>()
.Map(m =>
{
m.Properties(b => new {b.GameId});
m.ToTable("Details");
});
}
How can i bind it correctly with a 1-1 relationship?
You shouldn't use Map
to configure a one-to-one relationship. Use the relationship methods of the fluent API instead.
Have a look at http://msdn.microsoft.com/en-us/data/jj591620.aspx#RequiredToRequired .
如果覆盖OnModelCreating,则不应具有属性属性。
OK, You can also do it using Data Annotation attributes:
The code can look like the following:
public class Game
{
[Key]
public int GameId { get; set; }
public string GameName { get; set; }
//Navigation prop
public virtual Details GameDetails { get; set; }
}
public class Details
{
[Key]
[ForeignKey("Game")]
public int GameId { get; set; }
public int RatingId { get; set; }
public int Grade { get; set; }
//Navigation prop
public virtual Game Game{ get; set; }
public virtual RatingCompany RatingCompany { get; set; }
}
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.