Torna al Blog

    Views from MSSQL in Entity Framework without a primary key

    12 settembre 2014

    Often we need to import an SQL view into Entity Framework, and many times the view is the result of UNION, GROUP BY and similar commands, so it has no obvious key. Entity Framework, however, needs a primary key (or something it can use as one) on every object.

    You can use the following rules:

    • To force Entity Framework to use a column as a primary key, wrap it in ISNULL.
    • To force Entity Framework not to use a column as a primary key, wrap it in NULLIF.

    An easy way to apply this is to wrap the select statement of your view in another select:

    SELECT
        ISNULL(MyPrimaryID, -999) AS MyPrimaryID,
        NULLIF(AnotherProperty, '') AS AnotherProperty
    FROM ( ... ) AS temp

    Entity Framework infers the key from the nullability of the columns: a non-nullable column becomes part of the key, a nullable one does not.