dotnetcore EF 使用外键值但不引入join子句

某些情况下,出于性能考虑,我们需要外键的id值,但不想使用join子句把引用类型都读进来。

    class Book
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Author { get; set; }
        public int Age { get; set; }
        public Person Owner { get; set; }
        public int OwnerId { get; set; }  // 引入这个OwnerId, 等于Owner.Id

        public override string ToString()
        {
            return $"name:{Name}, author:{Author}, owner:{Owner.Name}";
        }
    }

    class BookConfig : IEntityTypeConfiguration<Book>
    {
        public void Configure(EntityTypeBuilder<Book> builder)
        {
            builder.ToTable("Book");
            // nvarchar is changed to varchar, but length is decided by HasMaxLength(50).
            builder.Property(e => e.Name).HasColumnType("nvarchar(80)").HasMaxLength(50).IsRequired();
            builder.Property(e => e.Author).HasColumnName("author_name").HasMaxLength(100).IsRequired();

            builder.Ignore(e => e.Age);

            // 使用HasForeignKey()
            builder.HasOne<Person>(b => b.Owner).WithMany(p => p.Books).HasForeignKey(b => b.OwnerId).IsRequired();
        }
    }
        private static Task ReadPartial(MyDbContext ctx)
        {
            // sql becomes: select id, name from book.
            var book = ctx.Books.Select(b => new { b.Id, b.Name }).First();
            Console.WriteLine(book.Name);

            // use ownerId to get Owner's id without join sub clause.
            var book2 = ctx.Books.Select(b => new { b.Id, b.Name, b.OwnerId }).FirstOrDefault();
            Console.WriteLine(book2.OwnerId);

            return Task.CompletedTask;
        }

dotnetcore EF 使用外键值但不引入join子句

可以看到上述sql语句没有join子句。

上一篇:1月28日对话框AlertDialog


下一篇:elasticsearch系统学习笔记3-数据基本操作