【发布时间】:2018-03-16 12:25:01
【问题描述】:
我正在创建一个 ASP.net Core 2 应用程序。我想在项目中使用现有的 MS-SQL 数据库。
我已经使用以下命令添加了数据库:
dotnet ef dbcontext 脚手架 “服务器=XXXX;数据库=XXXX;Trusted_Connection=True;IntegratedSecurity=False;用户 Id=XXXX;密码=XXXX" Microsoft.EntityFrameworkCore.SqlServer --output-dir 模型/数据库
在数据库中有如下连接:
Persons ----- PersonsGroupRelationships ----- 组
在实体框架中类似于
db.Persons.First().Groups
应该可以。 (在其他 MVC 5 应用程序中它工作完美)但只有 Persons 属性正确加载。连接始终包含 null。
即使我在实体框架中选择的人在代码中具有组关系,我也会返回一个空值。
如您所见,我介绍的正常属性工作正常,但数据库中的每个关系都存在问题。
在模型中实现连接:
Persons.cs 包含:
public Persons()
{
Groups = new HashSet<Groups>();
PersonsCompaniesRelationships = new HashSet<PersonsCompaniesRelationships>();
PersonsGroupsRelationships = new HashSet<PersonsGroupsRelationships>();
SrmStudenten = new HashSet<SrmStudenten>();
}
...OtherStuff...
public Groups ResponsibilityGroupNavigation { get; set; }
public ICollection<Groups> Groups { get; set; }
public ICollection<PersonsCompaniesRelationships> PersonsCompaniesRelationships { get; set; }
public ICollection<PersonsGroupsRelationships> PersonsGroupsRelationships { get; set; }
public ICollection<SrmStudenten> SrmStudenten { get; set; }
DB-Context 文件包含:
modelBuilder.Entity<Persons>(entity =>
{
...OtherStuff...
entity.HasOne(d => d.ResponsibilityGroupNavigation)
.WithMany(p => p.Persons)
.HasForeignKey(d => d.ResponsibilityGroup)
.HasConstraintName("FK_Persons_Groups");
});
我希望你们中的任何人都可以帮助我:-)
更新:
我已经更改了 Microsoft Doc 告诉我延迟加载的代码
在我添加的上下文文件中:
optionsBuilder
.UseLazyLoadingProxies()
在课程中我将其更改为虚拟:
public virtual ICollection<Groups> Groups { get; set; }
public virtual ICollection<PersonsCompaniesRelationships> PersonsCompaniesRelationships { get; set; }
public virtual ICollection<PersonsGroupsRelationships> PersonsGroupsRelationships { get; set; }
public virtual ICollection<SrmStudenten> SrmStudenten { get; set; }
【问题讨论】:
-
你在使用延迟加载和虚拟属性吗? docs.microsoft.com/en-us/ef/core/querying/…
-
public ICollection<Groups> Groups { get; set; }不看起来virtual。 -
在“DB-Context”文件中,属性是虚拟的,不在类文件中。尽管如此,我测试了在类文件中添加 virtual 并没有改变:-(
-
您是否阅读了docs.microsoft.com/en-us/ef/core/querying/… 并添加了
ILazyLoader lazyLoader构造函数参数? -
EF-core 2.1 中的延迟加载仍处于预览阶段。不要指望它几乎可以完美地工作。而且,如前所述,在断开连接的情况下,急切加载更合适。
标签: c# asp.net asp.net-mvc entity-framework asp.net-core-2.0