[英]Entity Framework Core 2.2 Owned Entity with UseLazyLoadingProxies
我目前正在開發一個代碼庫,我想向其中添加一些具有相應擁有實體的新實體。 因為在我不會涉及的代碼庫的其他部分中,將調用UseLazyLoadingProxies
; 我收到以下異常:
System.InvalidOperationException:實體類型'FooOwner'上的導航屬性'Foo'不是虛擬的。 UseLazyLoadingProxies要求所有實體類型都是公共的,未密封的,具有虛擬導航屬性以及公共或受保護的構造函數。
如果將屬性標記為虛擬,則所擁有的實體將進入新表; 我也不想要
根據我遇到的github問題,這似乎是預期的行為。
我的問題是:是否有解決此問題的方法,這樣,我就可以以某種方式將擁有實體標記為與擁有者實體存儲在同一表中,並且如果可能的話,始終將其Include
d中,並使其熱切地加載。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.