Entity Framework 具有 UseLazyLoadingProxies 的核心 2.2 拥有的实体

Entity Framework Core 2.2 Owned Entity with UseLazyLoadingProxies

我目前正在开发一个代码库,我想向其中添加一些具有相应拥有实体的新实体。因为,在我不会触及的代码库的其他部分, UseLazyLoadingProxies 被调用;我收到以下异常:

System.InvalidOperationException : Navigation property 'Foo' on entity type 'FooOwner' is not virtual. UseLazyLoadingProxies requires all entity types to be public, unsealed, have virtual navigation properties, and have a public or protected constructor.

如果我将 属性 标记为虚拟,拥有的实体将进入一个新的 table;我也不想要。

根据我遇到的 github 个问题,这些似乎是预期的行为。

我的问题是:有没有办法解决这个问题,这样,我可以以某种方式将拥有的实体标记为与所有者实体存储在同一个 table 中,并且如果可能的话总是 Included,急切加载。

using System.Diagnostics;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using NUnit.Framework;

namespace WhosebugObjectContext.Tests
{
    public class Foo
    {
        public long Id { get; set; }
        public int Data { get; set; }
    }

    public class FooOwner
    {
        public int Id { get; set; }

        public Foo Foo { get; set; }
    }

    public class FooOwnerMap : IEntityTypeConfiguration<FooOwner>
    {
        public void Configure(EntityTypeBuilder<FooOwner> builder)
        {
            builder.HasKey(x => x.Id);
            builder.HasOne(x => x.Foo);
        }
    }

    public class WhosebugObjectContext : DbContext
    {
        public WhosebugObjectContext(DbContextOptions options) : base(options) { }

        DbSet<FooOwner> FooOwners { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.ApplyConfiguration(new FooOwnerMap());
            base.OnModelCreating(modelBuilder);
        }
    }

    [TestFixture]
    public class WhosebugTest
    {
        WhosebugObjectContext _objectContext;

        [SetUp]
        public void SetUp()
        {
            var builder = new DbContextOptionsBuilder<WhosebugObjectContext>()
                .UseSqlServer(@"Data Source=.\SQLEXPRESS;Initial Catalog=Whosebug;Integrated Security=True")
                .UseLazyLoadingProxies();

            _objectContext = new WhosebugObjectContext(builder.Options);
        }


        [Test]
        public void CanGenerateCreateScript()
        {
            var script = _objectContext.Database.GenerateCreateScript();

            Debug.WriteLine(script);
        }

    }
}

您应该使用 OwnsOne 而不是 HasOne