实体框架核心 2.2 拥有的实体与 UseLazyLoad代理



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

System.InvalidOperationException : 实体类型"FooOwner"上的导航属性"Foo"不是虚拟的。UseLazyLoad代理要求所有实体类型都是公共的、未密封的、具有虚拟导航属性的,并且具有公共或受保护的构造函数。

如果我将属性标记为虚拟,则拥有的实体将进入一个新表;我也不想这样做。

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

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

using System.Diagnostics;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using NUnit.Framework;
namespace StackOverflowObjectContext.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 StackOverflowObjectContext : DbContext
{
public StackOverflowObjectContext(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 StackOverflowTest
{
StackOverflowObjectContext _objectContext;
[SetUp]
public void SetUp()
{
var builder = new DbContextOptionsBuilder<StackOverflowObjectContext>()
.UseSqlServer(@"Data Source=.SQLEXPRESS;Initial Catalog=StackOverflow;Integrated Security=True")
.UseLazyLoadingProxies();
_objectContext = new StackOverflowObjectContext(builder.Options);
}

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

你应该使用OwnsOne而不是HasOne

最新更新