是否可以在 Sql 服务器中定义一对多关系,并首先在实体代码中定义和使用这种关系的一侧

Is it possible define one-to-many relation in Sql Server and just define and use one side of this relation in entity code first

如果我在 Sql 服务器中定义了一对多关系外键约束,是否可以在一侧的代码优先 class 定义中定义和使用它? 例如,假设我有 Library 和 Book classes。每个图书馆可以有很多本书,但每本书属于一个图书馆。

public class Book
    {
        public Book() { }

        public int BookId { get; set; }
        public string BookName { get; set; }

        public virtual Library Library { get; set; }
    }

public class Library
    {
        public Library() { }
        public int LibraryId { get; set; }

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

如果我只想从书本端使用这个关系,我可以不在库 class 定义中定义下面的行吗?

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

当然,你可以这样做:

modelBuilder.Entity<Book>()
            .HasRequired(b => b.Library) // Or: HasOptional
            .WithMany()
            .Map(m => m.MapKey("LibraryId"))

在这种情况下,数据库 table Book 具有外键字段 LibraryId,它是必需的或可选的(可为空)。外键未映射到 class Book 中的 属性。这称为独立关联

如果需要,您还可以将密钥映射到 Book 中的 属性:

modelBuilder.Entity<Book>()
            .HasRequired(b => b.Library)
            .WithMany()
            .HasForeignKey(b => b.LibraryId))

这会将关联变成外键关联。在许多情况下 can be beneficial.