I am building my data layer using Entity Framework and I am trying to put reference fields of an entity into the key of that entity.
Using VS2010, .NET 4开发者_JAVA百科, EF 4.1, CodeFirst approach.
Given all that info please consider the following code sample:
public class Customer
{
[Key]
[Column(Order = 0)]
public int SetID { get; set; }
[Key]
[Column(Order = 1)]
public int CustomerId { get; set; }
public string CustomerName { get; set; }
}
public class Product
{
[Key]
[Column(Order = 0)]
public int SetID { get; set; }
[Key]
[Column(Order = 1)]
public int ProductId { get; set; }
public string ProductName { get; set; }
}
public class SalesVolume
{
[Key]
[Column(Order = 0)]
public Product product { get; set; }
[Key]
[Column(Order = 1)]
public Customer customer { get; set; }
[Key]
[Column(Order = 2)]
public DateTime SalesDate { get; set; }
public double Value { get; set; }
}
All my data is organized in sets, so Product and Customer entities have setID fields in them.
For SalesVolume, I have references to Product and Customer entities and I want those reference fields to be a part of my composite primary key for SalesVolume. Quite different from what I am asking, for the code above, EF generated the following table:
CREATE TABLE [dbo].[SalesVolumes](
[SalesDate] [datetime] NOT NULL,
[Value] [float] NOT NULL,
[product_SetID] [int] NULL,
[product_ProductId] [int] NULL,
[customer_SetID] [int] NULL,
[customer_CustomerId] [int] NULL,
PRIMARY KEY CLUSTERED
(
[SalesDate] ASC
)
Product and Customer references are placed with two fields each and they are not part of the primary key.
How can I tell EF to generate the SalesVolume table with only one setID field and with PK: (setID, productID, customerID)?
Thanks.
You actually just need to declare the foreign key relationship:
public class Customer
{
[Key]
[Column(Order = 0)]
public int SetID { get; set; }
[Key]
[Column(Order = 1)]
public int CustomerId { get; set; }
public string CustomerName { get; set; }
public virtual ICollection<SalesVolume> SalesVolumes {get; set;}
}
public class Product
{
[Key]
[Column(Order = 0)]
public int SetID { get; set; }
[Key]
[Column(Order = 1)]
public int ProductId { get; set; }
public string ProductName { get; set; }
public virtual ICollection<SalesVolume> SalesVolumes {get; set;}
}
public class SalesVolume
{
[Key]
[Column(Order = 0)]
public Product product { get; set; }
[Key]
[Column(Order = 1)]
public Customer customer { get; set; }
[Key]
[Column(Order = 2)]
public DateTime SalesDate { get; set; }
public double Value { get; set; }
}
精彩评论