简体   繁体   English

在没有所有键/外键的情况下在实体框架中创建导航属性

[英]Create Navigation Property in Entity Framework Without all keys/foreign keys

I have been trying to figure out if it is possible to create an association in EF without the use of all keys. 我一直试图找出是否有可能在不使用所有键的情况下在EF中创建关联。

Below is an example where there is a combination key in author, but I only have 1 part of that key in book. 下面是一个示例,其中作者中有一个组合键,但是我在书中只有一部分。 My question is how do I make a Navigation property without all of the keys? 我的问题是如何在没有所有键的情况下创建Navigation属性?

[Table("Book")]
public class Book {

    [Key]
    public int ID { get; set; }

    public string AuthorLastName { get; set; }

    public virtual Author Author { get; set; }
}

[Table("Author")]
public class Author {

    [Key, Column(Order=0)]
    public string AuthorFirstName { get; set; }

    [Key, Column(Order=1)]
    public string AuthorLastName { get; set; }

    public virtual ICollection<Book> Books { get; set; }
}

internal class BookConfig : EntityTypeConfiguration<Book> {
    public BookConfig()
    {
        HasRequired(hr => hr.Author)
            .WithMany(wm => wm.Books)
            .HasForeignKey(fk => new { 
                fk.AuthorLastName
            });
    }
}

This is obviously not going to work since I don't have all of the full combination key in book to associate it to author in this way. 这显然是行不通的,因为我在书中没有将全部组合键以这种方式关联到作者的所有键。

You can do something like that: 您可以执行以下操作:

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ID { get; set; }

This will give you a manual control on the key; 这将使您可以手动控制按键; But the Table in the database must have a primary key! 但是数据库中的表必须具有主键! I'm wonderung why ou need something like that I think the problem somewhere else. 我不知道为什么您需要这样的东西,我认为这是其他地方的问题。

You cannot do that because it's a many to many relation. 您不能这样做,因为这是多对多的关系。

In your example, if you only take AuthorLastName there can be several authors with the same last name. 在您的示例中,如果仅使用AuthorLastName则可以有多个具有相同姓氏的作者。 So there are many elements in this side of the relation. 因此,在关系的这一方面有许多要素。 And obviously there are many books on the other side (an author can write many books). 显然,另一边有很多书(作者可以写很多书)。

So, definitely, you cannot model it as a one-to-many relation. 因此,绝对不能将其建模为一对多关系。

Fortunately, someone has explained this problem of books and authors before. 幸运的是, 以前有人曾解释过书籍和作者的问题。 .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM