【发布时间】:2015-11-15 21:45:21
【问题描述】:
我有这样的类(简化):
public class Transaction
{
public int LocalId { get; set; }
public int MachineId { get; set; }
public virtual Machine Machine { get; set; }
public int? MoneyId { get; set; }
public virtual TransactionMoney Money { get; set; }
}
public class Machine
{
public int Id { get; set; }
public string Name { get; set; }
}
public class TransactionMoney
{
public int LocalId { get; set; }
public int MachineId { get; set; }
public virtual Machine Machine { get; set; }
public int TransactionId { get; set; }
public virtual Transaction Transaction { get; set; }
}
我想建立关系 Transaction 1 0...1 TransactionMoney,其中 Money 中的外键应该是 TransactionId 和 MachineId(连接到交易的 LocalId 和 MachineId)。我需要在 fluent API 中执行此操作。
我试过的是:
modelBuilder.Entity<Transaction>()
.HasOptional(t => t.Money)
.WithRequired(t => t.Transaction)
.HasForeignKey() <--- there is no such method
在另一边
modelBuilder.Entity<TransactionMoney>()
.HasRequired(t => t.Transaction)
.WithOptional(t => t.Money)
.HasForeignKey() <--- there is no such method
【问题讨论】:
-
Transaction的主键是什么? -
配对 LocalId 和 MachineId
-
好吧,那么
TransactionMoney也应该有一个主键LocalId, MachineId,它也是Transaction的FK。这就是在 EF 中实现 1:1 的方式。 -
就像@GertArnold 所说,您的模型完全不正确。
标签: c# entity-framework ef-fluent-api