且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

EF4.1 code首先复杂类型作为主键

更新时间:2022-10-14 23:01:01

这是限制。键部件可以直接在实体是唯一标量属性。复杂类型是重新presented作为不被支持的复杂属性

I'm currently trying to implement the repositories for my domain objects with the RC of Entity Framework 4.1 and its code first approach. Now I have a domain entity "Voyage" which has a unique identifier encapsulated in the type "VoyageNumber"

public class VoyageNumber
{
    private readonly string number;

    public VoyageNumber(string number)
    {
        Validate.NotNull(number, "VoyageNumber is required");

        this.number = number;
    }

    public string Id
    {
        get { return number; }
    }

Now I get an exception when i do this in the configuration of my DbContext:

modelBuilder.Entity<Voyage>().HasKey<VoyageNumber>(k => k.VoyageNumber);

The property 'VoyageNumber' cannot be used as a key property on the entity 'Domain.Model.Voyages.Voyage' because the property type is not a valid key type. Only scalar types, string and byte[] are supported key types.

and also when I try this:

modelBuilder.Entity<Voyage>().HasKey<string>(k => k.VoyageNumber.Id);

The properties expression 'k => k.VoyageNumber.Id' is not valid. The expression should represent a property: C#: 't => t.MyProperty'

Do I really have to trash my VoyageNumber and replace it with a primitive type?

This is the limitation. Key members can be only scalar properties directly in the entity. Complex type is represented as complex property which is not supported.