如何使用C#.Net中Customer中的属性Orders访问Order类属性

时间:2018-02-27 11:58:04

标签: c# .net linq

public class Customer
{
    [Key]
    public int CustomerId { get; set; }

    public string CustomerName { get; set; }

    public string CustomerLocation { get; set; }

    public Order[] Orders { get; set; }
}

[Table("Orders")]
public class Order
{
    [Key]
    public Nullable<int> OrderId { get; set; }

    public string OrderName { get; set; }

    public Nullable<DateTime> OrderDate { get; set; }
}

public  class CustomerContext:DbContext
{
    public CustomerContext()
        :base("name=CustomerContext")
    {
    }

    public DbSet <Customer> Customers { get; set; }
}

public class OrderContext : DbContext
{
    public OrderContext()
        :base("name=OrderContext")
    {
    }

    public DbSet<Order> Orders { get; set; }
}

我无法使用Order类中的订单属性设置并获取Customer属性我能够使用上下文类的对象获取和设置数据但无法设置或获取订单类属性的值。有人可以建议如何采用这种方法吗?

1 个答案:

答案 0 :(得分:0)

首先,Order中的OrderId不应该是可空的,因为它是主键。 订单类应具有Customer属性。

您只能使用一个具有两个属性的上下文类

public DbSet <Customer> Customers { get; set; }
public DbSet<Order> Orders { get; set; }

这样的事情:

public  class CustomerContext:DbContext
{
    public CustomerContext()
        :base("name=CustomerContext")
    {
    }

    public DbSet <Customer> Customers { get; set; }
    public DbSet<Order> Orders { get; set; }
}

尝试使用Order类:

[Table("Orders")]
public class Order
{
    [Key]
    public int OrderId { get; set; }

    [ForeignKey("Customer")]
    public int CustomerId { get; set; }

    public string OrderName { get; set; }

    public Nullable<DateTime> OrderDate { get; set; }

    public Customer Customer {get; set; }
}