logo
down
shadow

ASP.NET 5 Console Application (package) - How to create DBContext from connection string?


ASP.NET 5 Console Application (package) - How to create DBContext from connection string?

Content Index :

ASP.NET 5 Console Application (package) - How to create DBContext from connection string?
Tag : chash , By : user187383
Date : November 26 2020, 09:01 AM

I wish this helpful for you DbContext doesn't have this constructor anymore. You can specify the connection string in OnConfiguring method overload:
public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {         
        optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;");

    }
}

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Get connection string in console application


Tag : .net , By : Edo
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further Your connection string is called DBEntities
Use this line in your code instead:
String connString = ConfigurationManager.ConnectionStrings["DBEntities"].ConnectionString;

How to pass connection string to DBContext in Onion architecture application?


Tag : asp.net-mvc , By : robinator
Date : March 29 2020, 07:55 AM
will help you
How do I pass this connection string to Repository or DBContext so that it can be passed to DBContext constructor?
string conStr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;

container.Register<DBContext>(() => new DBContext(conStr));

Create a console application that opens a TCP/IP connection and print the inputted string - in C++, C# or Java


Tag : java , By : cmhudson
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further This tutorial has everything you need to know, and in fact very closely matches your specificationlet:
http://docs.oracle.com/javase/tutorial/networking/sockets/readingWriting.html
    String hostName = args [0];
    int portNumber = Integer.parseInt(args [1]);
    String transmit = args [2];

    try (
        Socket echoSocket = new Socket(hostName, portNumber);
        PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))
    )
        {
            out.println(transmit);
            String response = in.readLine ();
            while (response != null) {
                System.out.println("echo: " + response);
                response = in.readLine ();
            }
        }

Can't run EF migration where DbContext connection string is set at runtime and separate project from application


Tag : chash , By : Stephen Dewar
Date : March 29 2020, 07:55 AM
wish helps you Okay, so after much looking, you can't do this by default. No tooling for class libraries since January at all, which seems horrible to me. And no tooling as the link I posted mentions for a .NET CORE class library targeted at 461 using EF6, because EF6 tools do not recognize project.json dependency format.
However, blessed be, a gentleman by the name of Mohammad Rahhal created such a library to accomplish this: https://github.com/mrahhal/Migrator.EF6/blob/master/README.md
{
  "version": "1.0.0-*",

  "dependencies": {
    "EntityFramework": "6.1.3",
    "Migrator.EF6.Tools": "1.0.5"
  },

  "frameworks": {
    "net461": {}
  },

  "buildOptions": {
    "emitEntryPoint": true
  },

  "tools": {
    "Migrator.EF6.Tools": {
      "imports": "portable-net45+win8+dnxcore50",
      "version": "1.0.5"
    }
  }
}
public class Program
{
    public static void Main(string[] args)
    {
    }
}

What's a good pattern to create DbContext when dynamic data determines connection string


Tag : chash , By : fstender
Date : March 29 2020, 07:55 AM
To fix the issue you can do You can move your logic for creating ClientContext into another responsible class (according to SOLID principles), something like DbContextFactory and store there created DbContext's for each client. Like this:
public class DbContextFactory
{
    private readonly IConfiguration _configuration;
    private readonly Dictionary<string, ClientDbContext> _clientContexts = new Dictionary<string, ClientDbContext>();

    public DbContextFactory(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public ClientDbContext GetOrCreateClientContext(string clientNumber)
    {
        // if you have context already created - return it
        if (_clientContexts.ContainsKey(clientNumber))
            return _clientContexts[clientNumber];

        var optionsBuilder = new DbContextOptionsBuilder<ClientDbContext>();
        var clientConnection = string.Format(_configuration.GetConnectionString("clientConnection"), clientNumber);
        optionsBuilder.UseSqlServer(clientConnection);

        var clientDbContext = new ClientDbContext(optionsBuilder.Options);
        _clientContexts[clientNumber] = clientDbContext;

        return clientDbContext;
    }
}
public class Worker
{
    private readonly DbContextFactory _factory;

    public Worker(DbContextFactory factory)
    {
        _factory = factory;
    }

    public async Task DoWorkAsync()
    {
        // group by ClientNumber
        var groupedCases = caseList.GroupBy(x => x.ClientNumber);

        foreach (var groupedCase in groupedCases)
        {
            // For each client create context and repository
            var clientContext = _factory.GetOrCreateClientContext(groupedCase.Key);
            var clientRepository = new ClientRepository(clientContext);

            foreach (var @case in groupedCases)
            {
                var updatedCase = // transform case here
                await clientRepository.CreateCases(updatedCase);
            }
        }
    }
}
var factory = new DbContextFactory(yourConfiguration);
var worker = new Worker(factory);
await worker.DoWorkAsync();
Related Posts Related QUESTIONS :
  • Passing incorrect values into MultiValueConverter by MultiBinding
  • Can i use IEnumerator as Update func?
  • How to convert API Json response to C# Array?
  • Blazor Textfield Oninput User Typing Delay
  • Performing both layout and render transform results in wrong output
  • uwp beforetextchanged cursor moving in front of text
  • How to keep duplicates from a string[] exclude words from a List and print them out
  • .Net Core Strings.Asc/Mid/Chr/Len missing even after importing Microsoft.VisualBasic
  • How to return to previous search page without being asked to Confirm Form Re-submission and keeping the results on ASP.N
  • How set a identity scaffolding item/page how initial page in asp.net MVC core?
  • LINQ isn't calling Dispose on my IEnumerator when using Union and Select, expected behavior or bug?
  • What is "ByteArray.uncompress()" in AS3 equivalent to in C#?
  • Getting a specific letter from a string variable for my simple guessing game for clues
  • Send an email with Outlook without a subject --- dialog box issue
  • passing List<MyModel> from my controller in the "WebInterfaceProject" to the processor method in "D
  • How to convert Word document created from template by OpenXML into MemoryStream?
  • How can I make a single slider that changes the color of an object?
  • Remap JSON parameter in c#
  • What is the difference between "this ref" and "ref this" when talking about C# 7.2 ref extension met
  • Convert OpenSSL encryption into native C#
  • Accessing Properties in Razor Pages
  • How to get SOAP element value
  • Projection after Group
  • C# error cannot convert sytem.text.regularexpressions.match to string
  • Issues with Save/Load System in a Text Based Adventure game made with ScriptableObjects in Unity
  • VS2019 MSBuild.exe - ASP .Net MVC project fails to publish when using PublishProfile, but works when using OutDir parame
  • Does <pages validateRequest="false" /> in Web.config still matter?
  • How to send new request to redirect URL with new access token
  • Attempt to invoke virtual method on a null object reference Xamarin LockScreen
  • "The attribute names could not be inferred from bind attribute 'bind-value'" exception in Blazor
  • How to fix ''System.ArgumentException" in c#?
  • C#. Ref returning delegate for ref extension method
  • Swashbuckle Swagger generate an actual guid
  • Trying to make thousands of database calls simultaneously - they stack instead of running concurently
  • run mstest from cmd using testcontainer
  • How to make M:N (many-to-many) relationship where both M and N are the same entities?
  • Consume COM DLL from multiple clients
  • Convert json string response representing UCHAR array to Byte array
  • Why does this LinqPad program produce different results on the second run?
  • ServiceStack how to use MaxLoginAttempts feature
  • What does "late-bound access to the destination object" mean?
  • How to load appsettings.json inside a Static class based on deploy environment so that I can use in other class librarie
  • dynamically add images to view
  • Are static extension methods on User object safe?
  • Process thousands of database calls simultaneously
  • Trying to decrypt a string with public key(not private) using bouncycastle in .net
  • How to retrieve the name of an usb device
  • Query many-to-many related data using Entity Framework Core
  • ASP.NET MVC : how to find the view from a controller?
  • Inconsistent behaviour using Entity Framework for ASP.NET MVC app vs windows service
  • AutoFixture Customize vs Build
  • How to change textbox location at the click of a mouse in live mode?
  • How can I deserialize a XML file without defining the parent node?
  • asp.net core how decrease class coupling
  • ASP.NET Core Razor Pages Routing With parameters
  • String Escaping With $ Interpolation and @ Encoding
  • ConfigurationManager in ASP.NET WebAPI tested with HttpServer
  • Top down shooting in Unity 2D don't work as I want it to
  • Use own redirectUri when the Authentication expires
  • Using "foreach" in string array c#
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com