如何首先使用EF代码创建postgreSQL数据库

时间:2013-10-04 14:32:22

标签: c# entity-framework-5 code-first

我有两个班级Class1和Class2

[Table("CLASS1", Schema = "public")]
    public class Class1
    {
        public int Class1Id { get; set; }
        public string Name1 { get; set; }
    }

[Table("CLASS2", Schema = "public")]
    public class Class2
    {
        public int Class2Id { get; set; }
        public string Name2 { get; set; }

        public int Class1Id { get; set; }
        public virtual Class1 c1 { get; set; }

我定义了DatabaseContext:

public sealed class     DatabaseContext : DbContext
    {
        private static readonly DatabaseContext instance = new DatabaseContext();


        public static DatabaseContext Instance
        {
            get
            {
                return instance;
            }
        }

        private DatabaseContext()
            : base("maconnexion")
        {
            Database.SetInitializer<DatabaseContext>(null);

        }


        public DbSet<Class1> table1{ get; set; }
        public DbSet<Class2> table2{ get; set; }

    }

我将这些行添加到我的App.config

<DbProviderFactories>
      <add name="Npgsql Data Provider" invariant="Npgsql" description="Data Provider for PostgreSQL" type="Npgsql.NpgsqlFactory, Npgsql" />
    </DbProviderFactories>

 <connectionStrings>
    <add name="maconnexion"
 connectionString="Server=127.0.0.1;Port=5432;Database=DB_Ticketing;UserId=postgres;Password=slots2013;" providerName="Npgsql" />
  </connectionStrings>

我在PostgreSQL中创建了一个名为DB_Ticketing的数据库。但是当我执行我的代码时,表table1和table2没有添加到我的数据库中。

3 个答案:

答案 0 :(得分:1)

按如下方式配置您的应用程序: 步骤1(配置App.config)(复制并粘贴)

<?xml version="1.0"?>
 <configuration>
  <configSections>
   <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework,Version=6.0.0.0, Culture=neutral,PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
  </configSections>
   <connectionStrings>
    <add name="maconnexion" connectionString="User Id=postgres;Password=slots2013;Host=localhost;Database=DB_Ticketing;" providerName="Npgsql"/></connectionStrings>
  <startup>
  <supportedRuntime version="v4.0"sku=".NETFramework,Version=v4.0,Profile=Client"/>
  </startup>
   <entityFramework>
  <providers>
   <provider invariantName="Npgsql" type="Npgsql.NpgsqlServices,Npgsql.EntityFramework">
   </provider>
  </providers>
 <defaultConnectionFactory type="Npgsql.NpgsqlConnectionFactory,Npgsql"/>
   </entityFramework>
   <system.data>
   <DbProviderFactories>
  <remove invariant="Npgsql"></remove>
  <add name="Npgsql Data Provider" invariant="Npgsql" description="Data Provider for PostgreSQL" type="Npgsql.NpgsqlFactory, Npgsql"/>
   </DbProviderFactories>
</system.data>

步骤2(配置ContextDB)

 public class NameContext:DbContext   
 {
 public NameContext():base(nameOrConnectionString:"maconnexion"){}
    public DbSet<Class1> Class1s{ get; set; }
    public DbSet<Class2> Class2s{ get; set; }}

步骤3(调用方法Insert)

public static void Insert(Class1 o)
        {
         using (var context = new NameContext())
            { //Where "o" it is an object, for example Class1 o=new Class1();
                context.Class1s.Add(o);
                context.SaveChanges();
            }}

Nota:我建议使用DataAnnotations来创建您的业务类,例如:     [表(“MyTable”,Schema =“MySchema”)]     公共类ob_group     {         [键]         [柱( “nseq_grp”)]         public int Nseq_grp {get; set;} 有关详细信息,您可以看到: http://www.entityframeworktutorial.net/code-first/dataannotation-in-code-first.aspx 我希望它有用

答案 1 :(得分:0)

我知道已经有很长一段时间了,但是对于人们来说仍然有这篇文章。 这是最简单的信息。 基本的,如何配置。带有PostgreSQL的实体框架6:http://lvasquez.github.io/2014/11/24/EntityFramework-PostgreSql/

如何初始化代码。很有图形。 PostgreSQL的实体框架代码优先:https://dotblogs.com.tw/wuanunet/2016/02/26/entity-framework-code-first-postgresql

可选的。避免复数: How turn off pluralize table creation for Entity Framework 5?

注意:如果您决定不使用代码优先。记住PostgreSQL默认设置小写,所以定义是用小写装饰还是创建表区分大小写(创建表公用。&#34; XyZa&#34;)

答案 2 :(得分:0)

我使用sql查询做到了

SELECT 'public class '||c.table_name ||' { '|| 
 string_agg(case when c.character_maximum_length is not null then '[StringLength(' || to_char(c.character_maximum_length,'9999')||')]'  else '' end   ||
 'public ' ||
(case when c.datetime_precision is not null then ' DateTime' else 
case when c.numeric_precision is not null then ' int' else 'string' end  end)||
case c.is_nullable when 'YES' then '?'end ||  ' ' ||c.column_name,'{get;set;} ') ||' {get;set;} }'
  FROM information_schema.columns c
  where c.table_schema ='public'
 group by c.table_name