gpt4 book ai didi

c# - 关系 - EF Core

转载 作者:太空宇宙 更新时间:2023-11-03 14:45:04 25 4
gpt4 key购买 nike

我在进入 EF Core 关系时遇到了一些麻烦。

我不知道如何正确搜索它,所以我没有找到我需要的东西,但我找到了某个地方。

我有这两个类:

费用:

public class Expense : Entity
{

public string Title { get; set; }
public string Description { get; set; }
public decimal Amount { get; set; }
public List<ExpenseType> Types { get; set; }
public ValidationResult ValidationResult { get; private set; }

public bool IsValid
{
get
{
var fiscal = new ExpenseIsValidValidation();
ValidationResult = fiscal.Valid(this);
return ValidationResult.IsValid;
}
}}

费用类型:

 public class ExpenseType : Entity
{
#region properties
public string Name { get; private set; }
public string Description { get; private set; }
public ValidationResult ValidationResult { get; private set; }
public bool IsValid
{
get
{
var fiscal = new ExpenseTypeIsValidValidation();
ValidationResult = fiscal.Valid(this);
return ValidationResult.IsValid;
}
}}

在 ExpenseType 中的 ToListAsync 期间,EF 将“expenseId”列添加到查询中,但该列不存在。

我的数据库有三张表,一张代表类别,一张代表关系。(费用、费用类型和费用_费用类型)

通过在 StackOverflow 上寻找解决方案,我发现我应该为第三张表创建一个类。在这里:

 public class Expense_ExpenseType
{
public int ExpenseId { get; set; }
public Expense Expense { get; set; }
public int ExpenseTypeId { get; set; }
public ExpenseType ExpenseType { get; set; }
}

我的想法是,我可以有一个没有 Expense 的 ExpenseType,我也可以有一个没有 ExpeseType 的 Expense 或有多少我想要的 Expense。

所以 ExpenseType 没有任何费用。

我不确定我现在应该做什么。我应该使用 optionsBuilder 映射吗?如何?我应该重写数据库吗?

最佳答案

如果您想创建多对多关系,您有多种选择:

  1. 按照您的描述创建其他类。在这种情况下,EF 将创建表,您只能从该表中获取值。

    public class Expense_ExpenseType
    {
    public int ExpenseId { get; set; }
    public Expense Expense { get; set; }
    public int ExpenseTypeId { get; set; }
    public ExpenseType ExpenseType { get; set; }
    }
  2. 您可以不创建类而只是在上下文关系中进行描述。您将在其中描述所有内容,EF 将自行创建此表。但是从应用程序中您将看不到这张表。如果您不想使用其他字段扩展表,则必须使用此变体。

     modelBuilder
    .Entity<Student>()
    .HasMany<Course>(s => s.Courses)
    .WithMany(c => c.Students)
    .Map(cs =>
    {
    cs.MapLeftKey("StudentRefId");
    cs.MapRightKey("CourseRefId");
    cs.ToTable("StudentCourse");
    });

对于这种关系,您可以阅读更多 here

但在您的情况下,您不需要使用多对多。这就是为什么如果你不想在你的模型中添加属性 ExpanseTypeIdExpenseId 你可以这样描述它:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Expense>()
.HasMany<ExpenseType>(o => o.Types) //It is your list of expense types.
.WithOne() //Here you can add model for expense. To have an option go back from expense type to expense
.HasForeignKey("ForeignKey");//This key EF will create for you in DB but not in you app model
}

你想用什么你必须决定。如果您认为费用有很多费用类型,并且每个费用类型都有很多费用。您必须按照我的描述使用多对多。

关于c# - 关系 - EF Core,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54748894/

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