Domanda

Sto appena iniziando con Entity Framework 4.1, provando la modalità "Database First". Quando EF genera una classe modello con il generatore "Ado.net DBContext", non dovrebbe identificare la chiave primaria per la classe con un attributo [chiave]? Senza questo, sembra incompatibile con il t4 MVCaffolding.

Ecco i dettagli:

Utilizzando la GUI di progettazione del modello di dati di entità, ho aggiunto una semplice tabella "paese" al modello dal mio database esistente. La GUI identifica correttamente un singolo campo chiave di identità intera denominata "PK" come la mia chiave principale. (Ahimè! Sono un nuovo utente, quindi non posso aggiungere uno screenshot. Ho incluso il CSDL invece di seguito.) Tuttavia, quando EF genera codice utilizzando il generatore "Ado.net DBContext", non identifica il PK campo come campo chiave nella classe generata (vedi estratto del codice di seguito).

Il CSDL per la tabella "Paese":

<edmx:ConceptualModels>
  <Schema Namespace="EpiDataModel" Alias="Self" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation" xmlns="http://schemas.microsoft.com/ado/2008/09/edm">
    <EntityContainer Name="EpiModelEntities" annotation:LazyLoadingEnabled="true">
      <EntitySet Name="countries" EntityType="EpiDataModel.country" />
    </EntityContainer>
    <EntityType Name="country">
      <Key>
        <PropertyRef Name="PK" />
      </Key>
      <Property Name="PK" Type="Int32" Nullable="false" annotation:StoreGeneratedPattern="Identity" />
      <Property Name="Abbreviation" Type="String" Nullable="false" MaxLength="200" Unicode="false" FixedLength="false" />
      <Property Name="Name" Type="String" MaxLength="1024" Unicode="false" FixedLength="false" />
      <Property Name="Description" Type="String" MaxLength="1024" Unicode="false" FixedLength="false" />
      <Property Name="Sequence" Type="Int32" />
    </EntityType>
  </Schema>
</edmx:ConceptualModels>

Ecco il codice autogenerato:

//------------------------------------------------------------------------------
// <auto-generated>
//    This code was generated from a template.
//
//    Manual changes to this file may cause unexpected behavior in your application.
//    Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;

namespace MvcApplication1.Areas.Epi.Models
{
    public partial class country
    {
        public int PK { get; set; }
        public string Abbreviation { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public Nullable<int> Sequence { get; set; }
    }
}

Questo provoca un problema quando provo a impalcare un controller usando il modello T4 MVCAffolding. Ricevo un errore "Nessuna proprietà sembra essere chiavi primarie". Il comando e l'output dalla console del gestore dei pacchetti Nuget sono di seguito:

PM> scaffold controller MvcApplication1.Areas.Epi.Models.country -Area Epi -NoChildItems -DbContextType MvcApplication1.Areas.Epi.Models.EpiModelEntities -Force
Scaffolding countriesController...
Get-PrimaryKey : Cannot find primary key property for type 'MvcApplication1.Areas.Epi.Models.country'. No properties appear to be primary keys.
At C:\work\EPI\EPIC_MVC3\sandbox\MvcApplication1\packages\MvcScaffolding.1.0.6\tools\Controller\MvcScaffolding.Controller.ps1:74 char:29
+ $primaryKey = Get-PrimaryKey <<<<  $foundModelType.FullName -Project $Project -ErrorIfNotFound
    + CategoryInfo          : NotSpecified: (:) [Get-PrimaryKey], Exception
    + FullyQualifiedErrorId : T4Scaffolding.Cmdlets.GetPrimaryKeyCmdlet

Tuttavia, se cambio manualmente la classe generata per aggiungere un attributo [chiave] al campo, allora lo stesso comando identico mostrato sopra funziona bene:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; // manually added

namespace MvcApplication1.Areas.Epi.Models
{
    public partial class country
    {
        [Key]                        // manually added
        public int PK { get; set; }
        public string Abbreviation { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public Nullable<int> Sequence { get; set; }
    }
}

Allora perché il database EF non è primo e il T4 MVCaffolding giocando bene insieme? E anche senza il problema delle impalcature, le classi EF non devono sapere quali sono i campi chiave?

Nessuna soluzione corretta

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top