N
N
Nik Faraday2021-11-05 11:02:31
C++ / C#
Nik Faraday, 2021-11-05 11:02:31

How to connect Entity Framework Core to Windows Forms C# .Net Core?

Hello, I have a need to create a database on Windows Forms through Entity Framework Core.
I have not dealt with desktop applications for a long time, especially since I did not connect a database there.

I tried to transfer the ApplicationContext example from the asp.NET Core project and give a migration, in the package manager console I got "Build Failder" without explaining the cause of the error. ApplicationContext example below in the screenshot

public class UsersContext : DbContext
    {
        DbSet<AddressEntity> Addresses { get; set; }
        DbSet<WorkerEntity> Workers { get; set; }

        public UsersContext(DbContextOptions<UsersContext> options) : base(options)
        {
            Database.Migrate();
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(@"Data Source=localhost;Database=LabDb;Trusted_Connection=True;");
        }
    }


How can I solve this problem?

Upd: I changed the screenshot, I had .EnsureCreate() instead of Database.Migrate(), but it still doesn’t solve anything and the error is the same

Upd2: I recreated the ApplicationContext class on UsersContext, when I try to migrate, it gives the following error (On the screen below)

6184f8e8da87f189686205.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nik Faraday, 2021-11-05
@NikFaraday

The answer turned out to be quite an interesting thing. Having tried to run the project and call the semi-naked constructor of the ApplicationDbContext configuration class in the form constructor (the name is new because it was recreating the class), the compiler required to implement relationships between entities, which later turned out to be the right decision.
I mean, somewhere the links between the tables were written crookedly, but the package manager didn’t tell me about it ... More precisely, he didn’t tell me anything concrete at all. That’s all for
me)

V
Vasily Bannikov, 2021-11-05
@vabka

Upd2 has a link on how to solve your problem.
It describes how to make a design time connection factory so that ef can generate code

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question