Entity Framework 中的相似列关系
Similar Columns Relation in Entity Framework
我在 C# Winforms 上使用 Entity Framework 4。
我有一个 SQL 服务器数据库,其中包含 2 个 table,如下所示:
Users
table:
UserId (int) (PK)
UserName
Products
table:
ProductId (int)(PK)
ProductTitle
UserId1 (int) (foreign key referencing `UserId` in `Users` table)
UserId2 (int) (foreign key referencing `UserId` in `Users` table)
我正在使用 Entity Framework(包括模型中的外键列)在我的 C# 项目中对 SQL 服务器数据库进行建模。
然后我用这段代码获取记录:
Entities dbEnteties = new Entities();
dbEnteties.ContextOptions.LazyLoadingEnabled = false;
var dbe = dbEnteties.Products.Include("Users");
var result = dbe.ToList();
当我从数据库中获取记录时,我看到 UserId1
字段有数据,但 UserId2
字段是 Null
。
我的 C# 代码有什么问题?我该如何解决这个问题?!
您在产品 table 中有两个指向用户 table 的外键是完全可以的。我一直这样做,你这样做的理由很好。
由于您关闭了延迟加载,如果您希望查询自动加载导航属性,则需要明确地“.Include”导航属性。您将不得不弄清楚 Entity Framework 为您自动创建的导航属性的名称。我假设您使用的是 "Database First" 模型。如果是这种情况,请双击您的 .EDMX 文件并查看产品 table。您应该在那里看到一个名为 "Navigation Properties" 的部分。它们可能被称为 "User" 和 "User1"。如果是这种情况,那么您需要执行以下操作。由于 table 之间有两个独立的关系,因此您将需要两个独立的“.Include”语句:
dbEnteties.Products.Include(product => product.User);
dbEnteties.Products.Include(product => product.User1);
(确保在文件的最顶部包含 using System.Data.Entity;,否则 lambda 语法将不起作用。)
我在 C# Winforms 上使用 Entity Framework 4。
我有一个 SQL 服务器数据库,其中包含 2 个 table,如下所示:
Users
table:
UserId (int) (PK)
UserName
Products
table:
ProductId (int)(PK)
ProductTitle
UserId1 (int) (foreign key referencing `UserId` in `Users` table)
UserId2 (int) (foreign key referencing `UserId` in `Users` table)
我正在使用 Entity Framework(包括模型中的外键列)在我的 C# 项目中对 SQL 服务器数据库进行建模。
然后我用这段代码获取记录:
Entities dbEnteties = new Entities();
dbEnteties.ContextOptions.LazyLoadingEnabled = false;
var dbe = dbEnteties.Products.Include("Users");
var result = dbe.ToList();
当我从数据库中获取记录时,我看到 UserId1
字段有数据,但 UserId2
字段是 Null
。
我的 C# 代码有什么问题?我该如何解决这个问题?!
您在产品 table 中有两个指向用户 table 的外键是完全可以的。我一直这样做,你这样做的理由很好。
由于您关闭了延迟加载,如果您希望查询自动加载导航属性,则需要明确地“.Include”导航属性。您将不得不弄清楚 Entity Framework 为您自动创建的导航属性的名称。我假设您使用的是 "Database First" 模型。如果是这种情况,请双击您的 .EDMX 文件并查看产品 table。您应该在那里看到一个名为 "Navigation Properties" 的部分。它们可能被称为 "User" 和 "User1"。如果是这种情况,那么您需要执行以下操作。由于 table 之间有两个独立的关系,因此您将需要两个独立的“.Include”语句:
dbEnteties.Products.Include(product => product.User);
dbEnteties.Products.Include(product => product.User1);
(确保在文件的最顶部包含 using System.Data.Entity;,否则 lambda 语法将不起作用。)