Net Core Project с базой данных Microsoft Access - PullRequest
0 голосов
/ 04 октября 2018

Я только что создал сетевой проект ядра, где мне нужно подключиться к базе данных Access с помощью EF.Я скачал пакет слепков с именем JetEntityFramework.

Это мой appsettings.json

    {
  "ConnectionStrings": {
    "DefaultConnection": "User ID=pasman; Password=root;  Server=localhost; Port=5432; Database=Todo; Integrated Security=true; Pooling=true;",
    "AccessConnection": "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\DBAccess.mdb; Jet OLEDB:Database Password=1234;"

  },

  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Это моя модель конфигурации

public class ClientConfiguration: IEntityTypeConfiguration<Client>
    { 
        public void Configure(EntityTypeBuilder<Client> builder)
        {
            builder.HasKey(prop => prop.ClientCode);

            builder.Property(prop => prop.ListCode).IsRequired();

            builder.Property(prop => prop.CodeResp).IsRequired();

            builder.Property(prop => prop.CodePassport).IsRequired();

            builder.Property(prop => prop.Name).IsRequired();

            builder.Property(prop => prop.Surname).IsRequired();

            builder.Property(prop => prop.Adress).IsRequired();

            builder.Property(prop => prop.City).IsRequired();


            builder.Property(prop => prop.Country).IsRequired();


        }
    }

Это моя модель

 public class Client
    {
        public int ClientCode{ get; set; }

        public int ListCode{ get; set; }

        public string CodeResp{ get; set; }

        public string CodePassport{ get; set; }

        public string Name{ get; set; }

        public string Surname{ get; set; }

        public string Adress{ get; set; }

        public string City{ get; set; }



        public string Country{ get; set; }
    }

Это мой клиентский контекст

public class ClientContext: DbContext
    {
        public DbSet<Client> Client{ get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseJet(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\DBAccess.mdb; Jet OLEDB:Database Password=1234");
        }

        public ClientContext( DbContextOptions<ClienteContext> options): base(options)
        {

        }

        protected override void OnModelCreating(ModelBuilder modelbuilder)
        =>modelbuilder.ApplyConfiguration(new ClientConfiguration());


}

Это мой стартовый класс

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);



            services.AddTransient<JetProviderServices>();




        }


        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }

Я новичок в этом, все, что я хочу сделать - это доступ к своемуполучить доступ к БД и сделать запрос, чтобы получить все клиенты, но я не знаю, как это сделать.В моем классе запуска я думаю, что мне нужно добавить свое конфигурационное соединение, как я делаю с сущностью, используя postgresql

services.AddEntityFrameworkNpgsql().AddDbContext <ClienteContext>(options =>
                               options.UseNpgsql(Configuration.GetConnectionString("AccessConnection")
                                 ));

Извините, если я плохо пишу.

...