hi i am generated an CRUD operations in entity frame work in mvc4. Now i Unit test that classes .. i am using the following code in controller for creation
[HttpPost]
public ActionResult Create(Member member)
{
if (ModelState.IsValid)
{
db.Members.Add(member);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(member);
}
and i am using the test code for testing this is,
[TestMethod]
public void Create()
{
MemberController me = new MemberController();
var mem = new Member();
mem.MemID = 123;
mem.MemName = "sruthy";
var result = (RedirectToRouteResult)me.Create(mem);
Assert.AreEqual("Index", result.RouteValues["action"]);
}
i am just try to test the create class. but it shows the following error
Test failed: Create
Message: Test method SmpleTest.MemberTest.Create threw exception:
System.data>ProviderIncomactibleException:An error occured while
getting provider information from the database. This can be cased by
Entity Framework using an incorrect connection string. Check the inner
exception for details and ensure that the connection string is
correct.--->System.data.ProviderIncompatibleException:The provide did
not return a ProviderManifestToken string.--->
System.Data.SqlClient.SqlException:A network- related or intace
specific error occured while establishing a connection to SQL Server.
The server was not found or was not accesable. Varify that the
instance name is correct and the SQL Server is configured to allow
remote connections.(proider:SQL Network Interfaces, error:26-Error
Locating Server/Instance Specified)
This is my connection string
<connectionStrings>
<add name="SampleDataContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=Sample;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\Sample.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>
Normally Create operation is worked with this connection string. Can anybody please help me to identify the problem. Thank you
Please add the connection string in test case project and your return action is Create not the Index.
Related
I just have...
public TEntity GetSingle(ISpecification<TEntity> Specification)
{
//return this._Context.CreateDbSet<TEntity>()
// .SingleOrDefault<TEntity>(Specification.SatisfiedBy());
if (Specification == null)
{
throw new ArgumentNullException("Specification");
}
IEnumerable<TEntity> source = this._Context.CreateDbSet<TEntity>().Where(Specification.SatisfiedBy()).AsEnumerable<TEntity>();
if (source.Count<TEntity>() > 0)
{
return source.First<TEntity>();
}
return default(TEntity);
}
... which gives me an error when trying to execute this._Context.CreateDbSet()
The error is marked green and the message is something like:
Exception of type 'System.Data.Entity.Core.MappingException' at mscorlib.dll but it was not caught by user code.
Additional Information: Schema specified is not valid. Errors:
Models.Company.CompanyModel.msl(3,4) : error 2062: No mapping specified for instances of the EntitySet and AssociationSet in the EntityContainer iOfferEntities.
I have the following connection strings at Web.config and App.config like...
<add name="iOfferEntities" connectionString="metadata=res://*/Models.Company.CompanyModel.csdl|res://*/Models.Company.CompanyModel.ssdl|res://*/Models.Company.CompanyModel.msl;provider=System.Data.SqlClient;provider connection string="data source=192.168.1.31;initial catalog=mto3;persist security info=True;user id=myuserid;password=mypassword;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
I have a connection to another database in the same server which I can work with no problems.
Any idea?
Thank you!!!
Well, I created a new model and got rid of the problematic one. Problem solved so far. Thanks anyway to all.
I read:
This ASP.NET page
whatched through the whole EF part of this pluralsight tutorial
And read nearly every web page ( including SO ones ) containing this error:
Format of the initialization string does not conform to specification starting at index 0
I still do not understand why this connection string is invalid:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-couleur-emotion.mdf;Initial Catalog=aspnet-couleur-emotion;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
My DBContext looks like this:
namespace couleur_emotion.Models
{
public class CouleurEmotionDB : DbContext
{
public CouleurEmotionDB()
: base("name==DefaultConnection")
{
}
public DbSet<PageModel> Pages {get;set;}
}
}
I've tried many different connection strings. Not even once was the database file even created. IT fails at the first call to:
var model = _db.Pages.ToList();
When trying to create the DB. Note the above line is in a class containing:
CouleurEmotionDB _db = new CouleurEmotionDB();
Bit new on EF. I'm, creating application where user selects database from computer. and now i want to change connection string to match location of the database for example : this is current connection string that points to database location somewhere on disk (C:\Users\student\Documents\TestData.md) :
add name="test" connectionString="metadata=res://*/Model2.csdl|res://*/Model2.ssdl|res://*/Model2.msl;provider=System.Data.SqlClient;provider connection string='data source=(LocalDB)\v11.0;attachdbfilename="C:\Users\student\Documents\TestData.mdf";integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework'" providerName="System.Data.EntityClient" />
now when user selects new database from disk the connection sting needs to change to location where new database is located (C:\Users\student\Desktop\NewSelectedDatabase.mdf) :
add name="test" connectionString="metadata=res://*/Model2.csdl|res://*/Model2.ssdl|res://*/Model2.msl;provider=System.Data.SqlClient;provider connection string='data source=(LocalDB)\v11.0;attachdbfilename="C:\Users\student\Desktop\NewSelectedDatabase.mdf";integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework'" providerName="System.Data.EntityClient" />
now i've created filedialog so user can select database and to get its adress . i've also changed my edmax to to recive custom connection string :
public partial class Tester : DbContext
{
public Tester()
: base("name=Test")
{
}
public Tester(string customcs)
: base(customcs)
{
}
now my problem is what do i pass to constructor as custom connection string ? i hope you understood me because i'm realy bad at english and explainig things
When you have the EF designer up, on the properties window is a connectionstring setting. Once you have everything set as you like, clear that setting to none. It rewrites the generated code to accept a connection string passed in on instantiating.
var mything= new dbcontext (connstring)
Another option would be to just create a new class (.cs) file giving it the same namespace that your Tester EF context belongs to, and paste this in there:
public partial class Tester : DbContext {
public Tester(string _connectionString) : base(ConnectionString(_connectionString)) {
this.Configuration.ProxyCreationEnabled = false;
this.Configuration.AutoDetectChangesEnabled = false;
}
private static string ConnectionString(string _connectionString) {
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.ProviderConnectionString = _connectionString;
entityBuilder.Metadata = "res://*/Models.Tester.csdl|res://*/Models.Tester.ssdl|res://*/Models.Tester.msl";
entityBuilder.Provider = "System.Data.SqlClient";
return entityBuilder.ToString();
}
}
Notice it's a partial class (just like the auto-generated ones for Tester are) -- and so you're adding to the auto-generated class made by EF (again, make sure they're in the same namespaces, so it really is an addition to the partial class, not just you off making your own little one).
This way, you're adding a new construction instantiation (that's passing a connection string) that gets modified into the right entity-connection-string builder (via the private static ConnectionString method).
var myThing = new Tester(ConfigurationManager.ConnectionStrings["db_DBName"].ToString());
I have one line in the web.config for the connection:
<add name="db_DBName" connectionString="Data Source=DBSERVER;initial Catalog=DBNAME;" providerName="System.Data.SqlClient" />
the build target defines its transformantion, and I just pass the same string into the code all the time.
So I'm going through this tutorial that seems so simple but I can't seem to get it to work.
http://msdn.microsoft.com/en-us/data/gg685489
This is the error I'm receiving when running my app: "Keyword not supported: 'name'."
Now I've looked at other posts similar to mine and it seemed like the connection string was the issue. So I looked closely at but can't see any real differences.
<add name="BBCommercialSolutionsEntities"
connectionString="metadata=res://*/Models.BBCommercialSolutions.csdl|res://*/Models.BBCommercialSolutions.ssdl|res://*/Models.BBCommercialSolutions.msl;provider=System.Data.SqlClient;provider connection string="data source=MYSOURCENAME;initial catalog=MYDATABASENAME;multipleactiveresultsets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
In my CompanyController.cs class, I receive the error when using the .ToList().
public ActionResult Index()
{
//return View();
using (var db = new BBCommercialSolutionsEntities())
{
//return View(db.BBCSCompanies.ToList());
var tbl = db.BBCSCompanies;
var list = tbl.ToList();
return View(tbl.ToList());
}
}
And "new BBCommercialSolutionsEntities()" goes to my auto-generated template
public BBCommercialSolutionsEntities()
: base("name=BBCommercialSolutionsEntities")
{
}
Any ideas, thoughts, explanations, rants would help.
Just use BBCommercialSolutionsEntities
public BBCommercialSolutionsEntities() : base("BBCommercialSolutionsEntities")
{
}
We're having lots of problems trying to get the MvcMiniProfiler to work with our EF implementation of the Repository Pattern.
Error:
The entity type CustomEntityPewPewFooFoo is not part of the model for
the current context.
Ok. this is the code we've done.
Custom UnitOfWork Context class
public class UnitOfWork : DbContext
{
public UnitOfWork(string connectionString)
: base(GetProfiledConnection(connectionString))
{ }
private static DbConnection GetProfiledConnection(string connectionString)
{
var parsedConnectionString = new
EntityConnectionStringBuilder(connectionString);
var connection = new
SqlConnection(parsedConnectionString.ProviderConnectionString);
return ProfiledDbConnection.Get(connection);
}
public void Commit() { ... }
}
Add the factory settings stuff...
// NOTE: If this is not added, I get an error:
// Unable to find the requested .Net Framework Data Provider.
// It may not be installed.
// In web.config ...
<system.data>
<DbProviderFactories>
<remove invariant="MvcMiniProfiler.Data.ProfiledDbProvider" />
<add name="MvcMiniProfiler.Data.ProfiledDbProvider" invariant="MvcMiniProfiler.Data.ProfiledDbProvider" description="MvcMiniProfiler.Data.ProfiledDbProvider" type="MvcMiniProfiler.Data.ProfiledDbProviderFactory, MvcMiniProfiler, Version=1.7.0.0, Culture=neutral, PublicKeyToken=b44f9351044011a3" />
</DbProviderFactories>
</system.data>
And finally, add this extra stuff....
// global.asax, in Application_Start().. because I'm caching
// some database data on startup.
var factory = new SqlConnectionFactory(ConfigurationManager.ConnectionStrings[0].ConnectionString);
var profiled = new MvcMiniProfiler.Data.ProfiledDbConnectionFactory(factory);
Database.DefaultConnectionFactory = profiled;
LoadApplicationDataToBeCachedForAllRequests(); // Go and hit the Db! Go Forth!!!
My connection string...
<connectionStrings>
<clear />
<add name="XWing_SqlServer_EF" connectionString="metadata=res://*/SqlServer.XWingModel.csdl|
res://*/SqlServer.XWingModel.ssdl|
res://*/SqlServer.XWingModel.msl;provider=System.Data.SqlClient;
provider connection string='Data Source=Tarantino;Initial Catalog=XWing;Integrated Security=SSPI;MultipleActiveResultSets=True;'"
providerName="System.Data.EntityClient" />
</connectionStrings>
And finally (again), then edmx info ..
- Entity Container Name: XWingEntities
- Namespace: XWing.Repositories.SqlServer
- Filename: XWingModel.edmx
It might be that you have the same kind of problem I had here. Basically, if the UnitOfWork class is not in the same assembly as the edmx, it will not work.