title: Entity-Framework 5.0 with PostgreSQL
body: <p>I would like to use the Entity-Framework 5.0 as an O/R mapper with a PostgreSql database. I already read many HowTos but I'm still stuck. Maybe I don't get the whole idea behind the EF.</p>
  
  <p><strong>What I want:</strong></p>
  
  <ul>
  <li>I want to write the code by my own. Then put some attributes to the properties and classes to tell the EF how to map the objects (like I would do with NHibernate).</li>
  <li>I don't want to generate a database from my model - I just want to use an existing one.</li>
  </ul>
  
  <p><strong>Example Model:</strong></p>
  
  <pre><code>[Table("device")]
  public class Device
  {
      [Key]
      public int Id { get; set; }
  
      [StringLength(255)]
      public string Identifier { get; set; }
  }
  
  [Table("customer")]
  public class Customer
  {
      public Customer()
      {
          this.Devices = new List&lt;Device&gt;();
      }
  
      [Key]
      public int Id { get; set; }
  
      [StringLength(255)]
      public string Name { get; set; }
  
      // attribute required?
      public List&lt;Device&gt; Devices { get; set; }
  }
  </code></pre>
  
  <p><strong>What I did:</strong></p>
  
  <ul>
  <li>Wrote the code above</li>
  <li>Created a DatabaseContext class</li>
  <li>Added DbProviderFactories and connectionStrings in the app.config</li>
  <li>Generated ssdl, msl, csdl files with the EdmGen.exe tool and copied them in the project (these files are also available in the bin folder)</li>
  </ul>
  
  <p><strong>DatabaseContext:</strong></p>
  
  <pre><code>public class DatabaseContext : DbContext
  {
      static DatabaseContext()
      {
          Database.SetInitializer&lt;DatabaseContext&gt;(null);
      }
  
      public DatabaseContext()
          : base("PostgreSQL")
      {
  
      }
  
      public DbSet&lt;Customer&gt; Customers { get; set; }
      public DbSet&lt;Device&gt; Devices { get; set; }
  }
  </code></pre>
  
  <p><strong>app.config:</strong></p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;configuration&gt;
    &lt;configSections&gt;
      &lt;!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --&gt;
      &lt;section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /&gt;
    &lt;/configSections&gt;
    &lt;startup&gt;
      &lt;supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /&gt;
    &lt;/startup&gt;
  
    &lt;system.data&gt;
      &lt;DbProviderFactories&gt;
        &lt;remove invariant="Npgsql" /&gt;
        &lt;add name="Npgsql Data Provider" invariant="Npgsql" support="FF" description=".Net Framework Data Provider for Postgresql Server" type="Npgsql.NpgsqlFactory, Npgsql, Version=2.0.12.0, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7" /&gt;
      &lt;/DbProviderFactories&gt;
    &lt;/system.data&gt;
  
    &lt;connectionStrings&gt;
      &lt;add name="PostGreSQL" 
           providerName="System.Data.EntityClient" 
           connectionString="metadata=.;provider=Npgsql;provider connection string=&amp;quot;Server=asdf;Port=5432;User Id=asdf;Password=asdf;Database=asdf;enlist=true&amp;quot;" /&gt;
    &lt;/connectionStrings&gt;
  
  &lt;/configuration&gt;
  </code></pre>
  
  <p><strong>Test:</strong></p>
  
  <pre><code>using (DatabaseContext context = new DatabaseContext())
  {
      if (context.Database.Exists())
      {
          Console.WriteLine("yep");
      }
      else
      {
          Console.WriteLine("nope");
      }
  
      foreach (Customer c in context.Customers)
      {
          Console.WriteLine("Name={0}", c.Name);
      }
  }
  
  Console.ReadLine();
  </code></pre>
  
  <p><strong>Output &amp; Error:</strong></p>
  
  <p>"yep" .. which means the database exist.
  But when accessing the context.Customers property I get the following Exception:</p>
  
  <pre><code>The entity type Customer is not part of the model for the current context.
  </code></pre>
  
  <p><strong>Stacktrace:</strong></p>
  
  <pre><code>at System.Data.Entity.Internal.InternalContext.UpdateEntitySetMappingsForType(Type entityType)
     at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
     at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
     at System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator()
     at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable&lt;TResult&gt;.GetEnumerator()
     at EF5.Program.Main(String[] args) in c:\Users\tba\Documents\Visual Studio 2012\Projects\EF5\EF5\Program.cs:line 26
     at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
     at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
     at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
     at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
     at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
     at System.Threading.ThreadHelper.ThreadStart()
  </code></pre>
  
  <p><strong>What I don't understand:</strong></p>
  
  <ul>
  <li>What are the ssdl, msl, csdl files good for, if DataAnnoations are available?</li>
  <li>Why is the Customer class not part of the model for the current context?</li>
  </ul>
  
  <p>When using the EdmGen.exe Tool it generates also a ObjectLayer.cs file which contains an ObjectContext and entity classes. The problem with that is, the entity classes derive from EntityObject. If I want to use the entity classes as business classes this is a serious problem, because the classes can't derive from any other classes.</p>
  
  <p>Moreover I don't understand why it generates an ObjectContext.. every single HowTo I found uses the DbContext class.</p>
  
  <p><strong>Entity Customer class generated by the EdmGen tool:</strong></p>
  
  <pre><code>/// &lt;summary&gt;
  /// No Metadata Documentation available.
  /// &lt;/summary&gt;
  [EdmEntityTypeAttribute(NamespaceName="EF5", Name="Customer")]
  [Serializable()]
  [DataContractAttribute(IsReference=true)]
  public partial class Customer : EntityObject
  </code></pre>
  
  <p>I am confused :-) </p>
  
  <p><strong>Edit:</strong></p>
  
  <ul>
  <li>I am not using the ObjectLayer.cs file! And I also don't want to use it, due to the  inheritance problems I stated above. The partial Customer class is just an example to show what the EdmGen tool generates.</li>
  <li><p>When I remove the csdl, msl and ssdl files I get the following error:</p>
  
  <pre><code>At least one SSDL artifact is required for creating StoreItemCollection.
  </code></pre></li>
  <li><p>When I remove the metadata keyword from the connectionString property in the app.config I get the following error:</p>
  
  <pre><code>Some required information is missing from the connection string. The 'metadata' keyword is always required.
  </code></pre></li>
  </ul>
  
  <p><br/>
  <br/></p>
  
  <p><strong>Solution:</strong></p>
  
  <p>I finally figured out how it works. The connectionString in the app.config is wrong. The correct connectionString:</p>
  
  <pre><code>&lt;connectionStrings&gt;
      &lt;add name="PostgreSQL"
          connectionString="Server=asdf;Port=5432;User Id=asdf;Password=asdf;Database=asdf;"
           providerName="Npgsql" /&gt;
  &lt;/connectionStrings&gt;
  </code></pre>
  
  <p>I removed the metadata, provider and the provider connection string property from the connectionString. Like <a href="https://stackoverflow.com/users/475031/brice">Brice</a> said, the metadata files aren't necessary, so I just removed them.</p>
  
  <p>Also the Table-Attribute for the Device and the Customer class needs to specify the <strong>schema</strong>. Like this:</p>
  
  <pre><code>[Table("customer", Schema="public")]
  public class Customer
  </code></pre>