gpt4 book ai didi

asp.net - Entity Framework 从具有不同表关系主/外键场景的两个表中选择

转载 作者:行者123 更新时间:2023-12-04 02:44:03 30 4
gpt4 key购买 nike

我有两个示例表:

场景 1

表 1 - 成分

ingredientId(PK, int, not null)
userId(FK, int, not null)
timestamp(datetime, not null)

表 2 - 成分的附加信息

ingredientAdditionalInformationId(PK, int, not null)
ingredientId(FK, int, not null)
isApproved(bit, not null)
unitsConverted(bit, not null)

在代码后面选择句子:

public IQueriable GetIngredientData(int ingredientId)
{
using (var context = new MyEntities())
{
var result = context.Ingredient
.Where(i => i.ingredientId == ingredientId)
.Select(i => new
{
i.ingredientId,
i.userId
i.IngredientAdditionalInformation.FirstOrDefault(iai => iai.ingredientId = i.ingredientId).isApproved
i.IngredientAdditionalInformation.FirstOrDefault(iai => iai.ingredientId = i.ingredientId).unitsConverted
});

return result.ToList().AsQueriable();
}
}

或者使用 join 选择(我知道你可以使用方法语法来连接,但我可以更快地编写使用查询方法的连接)

public IQueriable GetIngredientData(int ingredientId)
{
using (var context = new MyEntities())
{
var result = from i in context.Ingredient
join iai in context.IngredientAdditionalInformation on i.ingredientId equals iai.ingredientId
where i.ingredientId == 1
select new
{
i.ingredientId,
i.userId
iai.isApproved
iai.unitsConverted
};

return result.ToList().AsQueriable();
}
}

使用 join 或 FirstOrDefault() 哪个更好/更快,或者我应该像下面的示例 2 那样编写不同的数据库表:

情景 2

表 1 - 成分

ingredientId(PK, int, not null)
userId(FK, int, not null)
timestamp(datetime, not null)

表 2 - 成分

ingredientId(PK, FK, int, not null) //WITHOUT PRIMARY (ingredientAdditionalInformationId) AUTO INCREMENT KEY)
isApproved(bit, not null)
unitsConverted(bit, not null)

因为我知道每一种成分都只有一个附加信息...

选择代码中的句子

using (var context = new MyEntities())
{
var result = context.Ingredient
.Where(i => i.ingredientId = 1)
.Select(i => new
{
i.ingredientId,
i.userId
i.IngredientAdditionalInformation.isApproved
i.IngredientAdditionalInformation.unitsConverted
});
}

我想知道哪个表设计(SCENARIO1 或 SCENARIO2)对于优化选择更好,如果我真的需要 ingredientAdditionalInformation 中的自动递增键,如果我知道每个成分只有一个条目并且这是正确的如何使用 Entity Framework ?

最佳答案

如果您要维护两个表之间的一对一关系,那么您的第二种设计会更好,因为它还将确保数据库中的引用完整性。

然后,您可以使该属性成为 Entity Framework 模型中的单个导航属性,并按如下方式简化您的 EF 查询。如果您在模型中启用了导航属性的延迟加载,那么如果您是

var result = from i in context.Ingredient.Include("IngredientAdditionalInformation") select i;

然后按如下方式访问属性:

i.IngredientAdditionalInformation.isApproved

但是,您真的需要一张额外的 table 吗?每个属性只有三个属性,我只需将它们组合到一个表中,然后您就可以立即使用所有属性。

关于asp.net - Entity Framework 从具有不同表关系主/外键场景的两个表中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19245772/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com