【发布时间】: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<Keyword> Keywords { get; set; }public virtual ApplicationUser User { get; set; }这将使用 virtual 关键字将实体相互链接 -
我只需要评论...从数据库的角度来看,到处使用
Id并不好。我鼓励您将表的Id列命名为:ExpenseId、InvoiceId等。
标签: c# entity-framework