【问题标题】:Entity framework with many one-to-zero-or-one relationships具有许多一对零或一关系的实体框架
【发布时间】:2016-01-05 01:02:27
【问题描述】:

我想在一个实体中实现许多一对零或一对一的关系,但是我在让它工作然后为它生成迁移时遇到了问题。

public class Invoice
{
    public int Id { get; set; }
    public int? MorningExpenseId { get; set; }
    public int? EveningExpenseId { get; set; }
    public Expense MorningExpense { get; set; }
    public Expense EveningExpense { get; set; }
}

public class Expense
{
    public int Id { get; set; }
    public int InvoiceId { get; set; }
    public Invoice Invoice { get; set; }
}
modelBuilder.Entity<Invoice>()
    .HasOptional<Expense>(p => p.MorningExpense)
    .WithRequired(g => g.Invoice);

modelBuilder.Entity<Invoice>()
    .HasOptional<Expense>(p => p.EveningExpense)
    .WithRequired(g => g.Invoice);

但我收到Schema specified is not valid. Errors: The relationship '...' was not loaded because the type '...' is not available. 的错误。 我还尝试在“费用”类中使用主复合键,例如:

public enum ExpenseType { Morning, Evening };
public class Expense
{
    public int Id { get; set; }
    public ExpenseType ExpenseType { get; set; }
    public Invoice Invoice { get; set; }
}

但是让它工作也没有运气。这应该如何使用 Fluent API 来实现?

【问题讨论】:

  • 我不需要使用可为空的 public int? MorningExpenseId { get; set; } public int? EveningExpenseId { get; set; } 而是使用我的 git 页面中的示例 public virtual List&lt;Keyword&gt; Keywords { get; set; } public virtual ApplicationUser User { get; set; } 这将使用 virtual 关键字将实体相互链接
  • 我只需要评论...从数据库的角度来看,到处使用Id 并不好。我鼓励您将表的Id 列命名为:ExpenseIdInvoiceId 等。

标签: c# entity-framework


【解决方案1】:

在实体框架中,应用程序类型必须与数据库类型匹配。关系必须具有虚拟键。

你必须这样编码

public class Invoice
{
    public int Id { get; set; }
    public int MorningExpenseId { get; set; }
    public int EveningExpenseId { get; set; }
    public virtual Expense MorningExpense { get; set; }
    public virtual Expense EveningExpense { get; set; }
}

public class Expense
{
    public int Id { get; set; }
    public int InvoiceId { get; set; }
    public virtual Invoice Invoice { get; set; }
}

【讨论】:

  • 已经注意到 Invoice 类中不需要 MorningExpenseId 和 EveningExpenseId,因为 Expense 类中不需要 InvoiceId。实体框架将处理关系中的 Id。
  • 你说得对,我不需要这两个 id,但还要注意它们可以为空,因为它们是可选的。此外,virtual 关键字是可取的,但不是强制性的,除非您想利用延迟加载。这是我正在使用的代码的简化版本,所以我对这些轻微的“错别字”表示歉意。但是,我的问题的重点是我没有让多个一对零或一关系起作用,得到了我在帖子中指出的错误。
猜你喜欢
  • 2015-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-18
  • 2013-11-24
  • 2021-09-21
  • 1970-01-01
相关资源
最近更新 更多