我想在一个实体中实现许多一对一或一对一的关系,但我遇到问题,让它工作然后为它生成迁移。
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.
的错误。
我也在尝试在'Expense'类中使用主复合键,如:
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实现这一点?
答案 0 :(得分:2)
在Entity框架中,appliation类型必须与Database类型匹配。关系必须具有虚拟关键字。
你必须像这样编码
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; }
}