Galma88
Galma88

Reputation: 2546

Entity framework Code First SQL Server View

I defined a view in my DB and then I wrote the entity definition in the code:

    [Persistence]
    [Table("ADMV_APPLICATION_OPTION")]
    public partial class ADMV_APPLICATION_OPTION
    {
        public string ID_APPLICATION_OPTION { get; set; }
        public string DS_APPLICATION_OPTION { get; set; }
        public byte FL_TYPE { get; set; }
        public Nullable<double> OPTION_NUM_VALUE { get; set; }
        public string OPTION_STR_VALUE { get; set; }
        public string OPTION_XML_VALUE { get; set; }
        public System.Guid GUID_DIVISION_SAP { get; set; }
        public string ID_DIVISION_SAP { get; set; }
        public string ID_PLANT { get; set; }
    }

When I execute my application I get the error

One or more validation errors were detected during model generation:

MES.Core.ADMV_APPLICATION_OPTION: : EntityType 'ADMV_APPLICATION_OPTION' has no key defined. Define the key for this EntityType.

Do I need a key also for the views?

thanks

Upvotes: 1

Views: 189

Answers (1)

M. Wiśnicki
M. Wiśnicki

Reputation: 6203

Your error clearly tell that you need add PrimaryKey. Views in EntityFramework also need PK. You can tell EF, some column may be used as PK, using ISNULL when you create view in SQL:

Create view SomeView
As
  Select 
      IsNull(YourUniqueId, -1) as YourUniqueId,
      ...
  From TableName

Or using Data Annotation use [Key] attribute, setting this attribute to ID_APPLICATION_OPTION be sure it is unique.

    [Persistence]
    [Table("ADMV_APPLICATION_OPTION")]
    public partial class ADMV_APPLICATION_OPTION
    {
        [Key]
        public string ID_APPLICATION_OPTION { get; set; }
        public string DS_APPLICATION_OPTION { get; set; }
        public byte FL_TYPE { get; set; }
        public Nullable<double> OPTION_NUM_VALUE { get; set; }
        public string OPTION_STR_VALUE { get; set; }
        public string OPTION_XML_VALUE { get; set; }
        public System.Guid GUID_DIVISION_SAP { get; set; }
        public string ID_DIVISION_SAP { get; set; }
        public string ID_PLANT { get; set; }
    }

Upvotes: 1

Related Questions