I'm learning MVC. I just need to clear something. I'm following THIS tutorial. This guy uses LocalDB to store Movie object. He just adds a connection string and then after adding controller, as described in tutorial, CRUD action methods are automatically added. that guy used sentence something like, "that's all you have to do to store your movie object in your localdb". Database is automatically created (code first approach). (I know how to work with Entity Framework, where we have to create some model to map our database). But this tutorial is confusing me. There's nothing mentioned about creating database etc. while his connection string contains a word, "Movie.mdf" (under Data Source). Finally, following him, I'm getting server not found error (26). Am i missing something, as new to MVC?
Got the solution. The problem actually was that I was not calling the base constructor for dbContext class. Because I was assuming that keeping the name of the connection string and my class same will be enough. But it didn't work, and no db was created. I changed it as following piece of code, and it worked.
public class myDbClass : DbContext
{
public myDbClass()
: base("myConString")
{
//logic;
}
}
connection string is first placed with the SAME name in web.config, so that it can look up for.
<connectionStrings>
<add name="myConString" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
Is Local Db installed on your machine? It's installed when you install MS SQL server, but I think you have a checkmark, it's not installed by default.
When you install EntityFramework from NuGet, localdb is the default in your web.config, so it's true there is normally nothing else to do, even if it might not be the best way.
Related
I am new to ASP.net MVC.
In my MVC application I wanted to have default login functions.
Already I have connection string like this for my entity framework connection to application,
<add name="TestDB2Entities" connectionString="metadata=res://*/EntittyModel.SchoolDBModel.csdl|res://*/EntittyModel.SchoolDBModel.ssdl|res://*/EntittyModel.SchoolDBModel.msl;provider=System.Data.SqlClient;provider connection string="data source=PRAGEETH-PC;initial catalog=TestDB2;user id=sa;password=sa123;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
Using that connection string I try to use the available function of default pre implemented login functions. I could not use that and show me following error.
“Unable to find the requested .Net Framework Data Provider. It may
not be installed.”
Then I try to create a new connection string as follow and then it worked fine,
<add name="TestDB2Entities1" connectionString="data source=PRAGEETH-PC;initial catalog=TestDB2;uid=sa;pwd=sa123;integrated security=sspi" providerName="System.Data.SqlClient" />
But I need to have only one connection string to suit for both scenarios. Is it possible to have one connection string instead of having two connection strings?Or is it ok to have multiple connection string in my application?
Prageeth,
Assuming you mean the default implementation from the MVC 4 Internet Application template in Visual Sutdio 2012, then you can (and should) have a single connection string. In the template the only one initially is in InitializeSimpleMembershipAttribute, but you will need to add more (see the footnote)
All you need to do is set the connection string name in your UsersContext class to that of your own. Do the same in the InitializeSimpleMembershipAttribute class, and also in any calls to WebSecurity.InitializeDatabaseConnection
If you are using code-first (which, by the way, is the simplest approach when you first use SimpleMembership) you can also:
move UserProfile from UsersContext into your own context, and delete UsersContext
change the references to UsersContext in AccountController and InitializeSimpleMembershipAttribute to your own context
Footnote
For more information about what SimpleMembership is, and how it works, see my answer to the question How do I use my own database with SimpleMembership and WebSecurity? What is MVC4 security all about?, and for the simplest way to use InitializeSimpleMembership, see my answer to this question
I am trying to use SimpleMembership in my MVC 4 for the first time and I already have an existing database and EF5 model created based on it! I searched a lot but I cant find how I could use it in my case and also to have everything under my own model.
It would be great if somebody can give me an idea how to do this.
Thanks
Purely as a point of reference, it might be a good idea to create a new Internet Application template of an ASP.NET MVC 4 Web Application project (i.e. via File > New Project).
If you look at the AccountController, as #zms6445 says, it is decorated with an InitializeSimpleMembership attribute. You can find the implementation of this attribute in the InitializeSimpleMembershipAttribute.cs file in the Filters folder within the root directory.
In here, this is the missing part of the puzzle - you need to hook up your existing database so that it is used by the SimpleMembershipProvider. This is the code you need:
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
try
{
if (!WebSecurity.Initialized)
{
WebSecurity.InitializeDatabaseConnection("CONNECTION_STRING_NAME", "USER_TABLE", "USER_ID_FIELD", "USER_NAME_FIELD", autoCreateTables: true);
}
}
catch (Exception ex)
{
throw new InvalidOperationException("Something is wrong", ex);
}
}
}
Some things to note:
CONNECTION_STRING_NAME is an entry in your web.config ConnectionStrings - you CANNOT use the model connection string here - the SimpleMembershipProvider does not recognise that format! You need to specify an System.Data.SqlClient connection string, e.g.
<add name="CONNECTION_STRING_NAME" connectionString="data source=SERVER;initial catalog=DATABASE;user id=USER;password=PASSWORD;" providerName="System.Data.SqlClient" />
USER_TABLE is the table in your database to hold extra user information, such as first name, surname etc. This is linked to the autogenerated tables via the USER_ID_FIELD.
USER_ID_FIELD is usually the primary key of your Users table. It must be of type int.
USER_ID_NAME is a unique name for the user, which could be an Email address.
autoCreateTables is set to true to ensure the tables required for the SimpleMembership to work are created if they don't already exist.
Of course, this code only gets fired if you hit a page via the AccountController, since this has been decorated by the attribute. You could put a breakpoint in there and see it in action.
This should get you started - the Internet Application template is a pretty good template to follow if you get stuck.
Hope this helps.
In your web.config in the appSettings tag, add the line
<add key="enableSimpleMembership" value="true"/>
SimpleMembership is built in so from here you simply need to write
[InitializeSimpleMembership]
above your public class AccountController: Controller
When you want to force a user to log in for a certain page you write in the pages controller
[Authorize]
That tables will be automatically generated in your database. If you want to add more fields to these tables you will need to simply google it.
Here's a link for more information http://weblogs.asp.net/jgalloway/archive/2012/08/29/simplemembership-membership-providers-universal-providers-and-the-new-asp-net-4-5-web-forms-and-asp-net-mvc-4-templates.aspx
I’m developing a MVC Website based in codeplex EFMVC solution, and I’m using Entity Framework and Repository, Unit of Work and Command Patterns. My website needs to be a SaaS solution (software as a service) multiple database.
In my legacy Asp.Net WebForms I have a XML file that holds all the different string connections and I’m trying to use the same strategy. So in my LoginController I create a command that has company (to identify in which database will be connected) username and password. At Validate() method in Domain project, I’m reading the XML to get the correct string connection based on company field. My problem is how can I set the DatabaseFactory or DbContext to use this selected connection string? It should be injected at the constructor? Any suggestion for doing this in the correct way, without “breaks the rules”?
Note that I’m using AutoFac for Dependency Injection.
Thanks for your attention.
Best Wishes,
Luiz Fernando Vall Dionizio
You can use the ResolveNamed feature of Autofaq to get different registration for the same Interface
For instance:
builder.Register<IDataContext>(x => new DataContext(connectionStringOne))
.Named<IDataContext>("CS1");
builder.Register<IDataContext>(x => new DataContext(connectionStringTwo))
.Named<IDataContext>("CS2");
and to resolve it
var context = ContainerAccessor.Container().ResolveNamed<IDataContext>("CS1");
Another way is to override the DataContext ctor and read the configuration from an shared location for that request.
I need to build a dynamic connection string as shown in this tutorial:
However this code is very above my skill level. Can any help guid me through this(be very specific, please)?
The tutorial states that we need to create a partial class, but where should does this class be placed?
My .edmx file is named DBModel.edmx
my .tt file is name TraxzDBContext.tt
The connection string need to be similar to the one that follows:
<add name="TraxzDBEntities"
connectionString="metadata=res://*/;
provider=System.Data.SqlClient;
provider connection string='Data Source=d5d3955e-1183-4e10-8892-9f9d005af0a8.sqlserver.sequelizer.com;
User ID=1;
Password=1;
Initial Catalog=dbd5d3955e11834e1088929f9d005af0a8;
MultipleActiveResultSets=True'"
providerName="System.Data.EntityClient" />
Or if there is a better method of creating a dynamic string in the same fashion that is created in the tutorial, let me know.
Thanks to anyone who solves this issue.
You can create a partial class in any place in the same assembly where your DBModel.edmx file is. Just make sure that you use the same namespace.
I need to be able to configure my connection string at run time, preferably from a config file would be the simplest solution. However, I can't use ConnectionString.FromAppSetting nor ConnectionString.FromConnectionStringWithKey. My data-access assembly is referenced from console apps, win forms, and web. And while I can add "Settings" to my project, it's only a dll and won't bring that app.config over with it to the actual applications build destination.
I don't expect this is too uncommon. What is typically the way this is handled? Is this a prime example of when to use dependency injection (one that I could configure from a separate file?) I'm feeding the connection string to my 'unit of work' object, but I'd like to do it statically as to build the config and sessionfactory only once.
I can definitely clarify if needed, but I'm not sure the best way to ask.
You can use hibernate.cfg.xml (it works on every plattaform).
Alternatively you can do the following
Inherit DriverConnectionProvider
override the ConnectionString property, and read the connection string from anywhere.
Supply your new connection provider to your nhibernate configuration in code or in xml.
You can use ServiceLocation inside your DriverConnectionProvider or you can use the EnhancedBytecodeProvider on unhaddins. Search Enhanced bytecodeprovider and Fabio Maulo on google.
Here is an example: Dynamically change user info in connection string