среда, 9 октября 2013 г.

Composite Keys in EF

1.
You can mark both ActivityID and ActivityName properties with Key annotation or you can use fluent API as described by @taylonr.
Edit:
This should work - composite key defined with annotations requires explicit column order:
public class ActivityType
{
    [Key, Column(Order = 0)]
    public int ActivityID { get; set; }

    [Key, Column(Order = 1)]
    [Required(ErrorMessage = "A ActivityName is required")]
    [StringLength(50, ErrorMessage = "Activity Name must not exceed 50 characters")]
    public string ActivityName { get; set; }

}
share|improve this answer

We don't use the annotations, instead we override the model builder, in which case you can do something like:
modelBuilder.Entity<Activity>().HasKey(a => new { a.ActivityId, a.ActivityName });
share|improve this answer

2.
First you would have to explicitly put in the PKs and FKs inside OrderDetails class:
public class OrderDetails 
{        
    public int OrderID { get; set; }
    public int ProductID { get; set; }

    public virtual Order Order { get; set; }
    public virtual Product Product { get; set; }

    public Decimal UnitPrice { get; set; }
    public int Quantity { get; set; }
    public Decimal Discount { get; set; }
}
Then with the following code you can specify the PKs for OrderDetailsConfiguration class:
(Please note that in Northwind database both OrderID and ProductID are PKs for OrderDetails table).
public class OrderDetailsConfiguration : EntityConfiguration<OrderDetails> 
{
    public OrderDetailsConfiguration() 
    {
        HasKey(od => new 
        {
            od.ProductID,
            od.OrderID
        });
    }
}
And also you can use RecreateDatabaseIfModelChanges strategy to force your database to be recreated every time you change the class model:
Database.SetInitializer<NorthwindDb>(
        new RecreateDatabaseIfModelChanges<NorthwindDb>());
The interesting point is that once you made these changes EF will automatically infer the FKs fromOrderDetails class and create the relationships to Orders and Products table on OrderID and ProductID based on the Conventions for Code First:
Code First will infer that any property named ‘’ (i.e. ProductsProductID), ‘’ (i.e. ProductProductID) or ‘’ (i.e. ProductID), with the same data type as the primary key, represents a foreign key for the relationship. If multiple matches are found then precedence is given in the order listed above. Foreign key detection will not be case sensitive.
share|improve this answer

Комментариев нет:

Отправить комментарий