1

我有一个与 Service 模型一对一关系的 Transaction 模型,然后 Service 模型有许多 ServiceAddons。

public class Transaction 
{
   public int TransactionId {get;set;}
   public string Username {get;set;}
   public Service OccasionService {get;set;}
}

public class Service 
{  
   [Key]
   public int TransactionId {get;set;}
   public Transaction Transaction { get; set; }
   public virtual IList<ServiceAddon> ServiceAddons { get; set; }
}

public class ServiceAddon
{
    public int ServiceAddonId { get; set; }
    public int TransactionId { get; set; }
    public int AddonId { get; set; }
    public decimal AddonPrice { get; set; }
    public virtual Addon Addon { get; set; }
}

现在包管理器控制台告诉我 OccasionServiceId 在 ServiceAddon 中不存在,所以我为它更改了 TransactionId,程序已编译但现在它显示 Invalid column OccasionServiceId。我该如何解决?

4

1 回答 1

2

您需要指定ForeignKeys,尝试这样的事情。我已经为不清楚的位添加了评论。

public class Transaction 
{
    [Key]
    public int TransactionId {get;set;}
    public string Username {get;set;}

    // Whatever the column is
    public int OccasionServiceId {get;set;}

    [ForeignKey("OccasionServiceId")] // What on Transaction points to Service's Key
    public Service OccasionService {get;set;}
}

public class Service 
{  
    // Ideally this would be called ServiceId instead?
    [Key]
    public int TransactionId {get;set;}

    // If this uses TransactionId then are you sure you don't need a Key that is ServiceId
    public Transaction Transaction { get; set; }

    [ForeignKey("TransactionId")] // What on ServiceAddon points at Service's Key
    public virtual ICollection<ServiceAddon> ServiceAddons { get; set; }
}

public class ServiceAddon
{
    [Key]
    public int ServiceAddonId { get; set; }

    // Don't you need a ServiceId here?

    public int TransactionId { get; set; }
    public int AddonId { get; set; }
    public decimal AddonPrice { get; set; }
    public virtual Addon Addon { get; set; }
}

如果我成功了,我的模型会是这样的:

public class Transaction 
{
    [Key]
    public int TransactionId {get;set;}
    public string Username {get;set;}
    public int ServiceId {get;set;}

    [ForeignKey("ServiceId")]
    public Service Service {get;set;}
}

public class Service 
{  
    [Key]
    public int ServiceId {get;set;}
    public int TransactionId {get;set;}

    [ForeignKey("TransactionId")
    public Transaction Transaction { get; set; }

    [ForeignKey("TransactionId")] // What on ServiceAddon points at Service's Key
    public virtual ICollection<ServiceAddon> ServiceAddons { get; set; }
}

public class ServiceAddon
{
    [Key]
    public int ServiceAddonId { get; set; }
    public int ServiceId {get;set;}

    [ForeignKey("ServiceId")]
    public Service Service {get;set;}
}
于 2013-03-03T13:05:16.953 回答