在实体框架中正确实施识别关系

在实体框架中正确实施识别关系

本文介绍了在实体框架中正确实施识别关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个实体作者其名称可以写0 .. 1 ..或许多实体 Book 必须由一个作者编写,谈论没有作者



这(我相信)会被归类为识别关系。使用 EntityTypeConfiguration ,以下是实现此识别关系的正确方法?

  public BookMapping()
{
HasRequired(book => book.Author)
.WithMany(author => author.Books)
.HasForeignKey(book = book.AuthorID);
}


解决方案

不是识别关系。这只是常见的一对多关系。为了使其识别,您还必须映射由 BookID AuthorID 组成的复合主键。

  HasKey(book => new {book.BookID,book.AuthorID}); 


Let's say I have an entity Author which has a name can write 0 .. 1 .. or many of the entity Book. The Book must be written by one Author, and it is not meaningful to talk of a Book with no Author.

This (I believe) would be classified as an identifying relationship. With the EntityTypeConfiguration, would the following be the correct way of implementing this identifying relationship?

public BookMapping()
{
    HasRequired(book => book.Author)
   .WithMany(author => author.Books)
   .HasForeignKey(book => book.AuthorID);
}
解决方案

It is not identifying relation. It is just common one-to-many relation. To make it identifying you must also map composite primary key consisting of BookID and AuthorID.

HasKey(book => new { book.BookID, book.AuthorID });

这篇关于在实体框架中正确实施识别关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 22:44