we use the nunit.exe application to run our (integration)test
Now i experience the problem that the connectionstring is not picked up from the app.config from the dll where the testcode is in.
That sounds logical because the nunit.exe is the starting app and not the test dll (it used to work when i started the tests from the visual studio testframework by the way), but should i put the connectionstrings in the nunit.exe.config?
I tried setting them in the testcode (works for the appsettings : ConfigurationManager.AppSettings.Set("DownloadDirectory", mDir);) like this:
ConfigurationManager.ConnectionStrings.Add(conset); (where conset is a ConnectionStringSettings object), but then i get the error that the connectionstrings section is readonly.
What should i do to use the connectionstrings in my test?
EDIT:
we use the entity framework so we can't put the connectionstring in the appsettings because it reads from the section directly, i couldn't find a way to work around this behaviour.
Using reflection, you can (in memory) change your value of the Configuration.ConnectionStrings[connectionName], which in your case you would probably do in SetUp or perhaps TestFixtureSetUp. See http://david.gardiner.net.au/2008/09/programmatically-setting.html.
// Back up the existing connection string
ConnectionStringSettings connStringSettings = ConfigurationManager.ConnectionStrings[connectionName];
string oldConnectionString = connStringSettings.ConnectionString;
// Override the IsReadOnly method on the ConnectionStringsSection.
// This is something of a hack, but will work as long as Microsoft doesn't change the
// internals of the ConfigurationElement class.
FieldInfo fi = typeof(ConfigurationElement).GetField("_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
fi.SetValue(connStringSettings, false);
// Set the new connection string value
connStringSettings.ConnectionString = connectionStringNeededForNUnitTest;
I realize this is not the answer you are looking for, but it is the one I applied to solve your same problem:
You can modify, in EF5 and EF4.3 at least, your DbContext implementation and add a constructor that accepts a hard coded connection string, such as this:
public partial class MyContext : DbContext
{
public MyContext() : base("name=MyContext")
{
}
// --- Here is the new thing:
public MyContext(string entityConnectionString) : base(entityConnectionString)
{
}
// --- New thing ends here
// .... the rest of the dbcontext implementation follows below
}
You would have to paste this thing in every time you regenerate your context, but IMHO it's worth the hassle. The connection string has to be entity framework formatted with your metadata and everything, but you will be able to figure it out. Just keep it somewhere so you can paste it in whenever necessary.
You can read Connection String Value from ConfigurationManager.AppSettings, yes it is readonly. You can change it in App.Config.
If you want to change some values in connection string, for ex URL, in code you can change your dataContext.URL or any properties you want with coding.
I think for unit tests it may be much easy. you may put connection string into a test class directly as hardcoded string. in simple unit tests you test limited logic scope and not care of authentically of input arguments
Related
I am writing a C# .NET 4.5-based Windows Forms application.
I'd like to set a flag (Boolean) in one of the classes (probably the main Form's class) that defines whether the app is running in Production of Debug mode. I will use this flag to control various actions of the app, including GUI-based actions as well as which connection string to use.
I don't have a problem with the GUI-based stuff because the flag is defined in the main Form's class, but I'm having a problem with the connection string. There is a separate class for DB access, which basically just defines a constant like this:
namespace MyApp
{
class DatabaseInterface
{
public static string MyConnectionString = "Data Source=server;Initial Catalog=db";
}
}
I'd like to change the connection string (really just the "server") depending on that production/debug flag. I do NOT want to put an if/then/else in every place where the connection string is used (to toggle between debug and production strings), but would like a single named connection string that can be used throughout the app. I'd also prefer to NOT have to instantiate a DatabaseInterface object (I know I could dynamically change this in the "get" definition of a public property of the DatabaseInterface class).
Is there a way to do this?
If you want to do this based on a flag and don't want the if everywhere, I'd suggest that you use a simple getter like this :
namespace MyApp
{
class DatabaseInterface
{
public static string getConnectionString()
{
return myFlag ? "Data Source=server;Initial Catalog=db" : "AnotherString";
}
}
}
I'm trying to write a unit test for my project, but it will not let me use the Configuration Manager. Right now my project is set up like
ASP.Net application (all aspx pages)
ProjectCore (all C# files - model)
ProjectTest (all tests)
in my ProjectCore, I am able to access the ConfigurationManager object from System.Configuration and pass information onto the project. However, when I ran a test where the ConfigurationManager is involved, I get the error
System.NullReferenceException: Object reference not set to an instance of an object.
Here is an example of the test
using System.Configuration;
[TestMethod]
public void TestDatabaseExists()
{
//Error when I declare ConfigurationManager
Assert.IsNotNull(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString
}
in my other tests, ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString is what I set my data adapter's configuration string to, and returns a null error on the tests but not when I actually use the website. Any ideas?
It could be one of several issues:
You didn't add app.config to your ProjectTest project.
You didn't add connection string in your app.config.
You are doing a unit test and in unit test your concentration should be the particular method trying to test and should remove extraneous dependencies. in this case, try mocking/moleing(use Microsoft Mole and Pex) system.configuration class; that will give a solution for sure.
What I am saying, once you install MS moles-and-pex -> in your test project solution -> right-click the system assembly and choose create mole.
That will give you a mole'ed version of configuration class which in turn will have a mocked version of configuration class -- using which you can bypass the problem you are facing.
You also can use special configuration paths with the ExeConfigurationFileMap:
// Get the machine.config file.
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
// You may want to map to your own exe.config file here.
fileMap.ExeConfigFilename = #"C:\test\ConfigurationManager.exe.config";
// You can add here LocalUserConfigFilename, MachineConfigFilename and RoamingUserConfigFilename, too
System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
It is related to the /noisolation parameter in the command line of mstest.exe.
Omitting the /noisolation parameter, it works.
first of all you must make sure that you have an app.config file in your nunit tests project.
To add it, you can open the project properties (right click on the project)
Enter the details of your connection, it will generate a app.config file or add the right section within :
In your Test class, add the reference to : System.Configuration;
=> using System.Configuration;
For example you could use your connectionString by this way :
[TestFixture]
public class CommandesDALUnitTest
{
private string _connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
[Test]
public void Method_Test()
{
string test = _connectionString;
....
}
}
I have a WinForm project that contains several UserControls. This WinForm project has a reference to an assembly (lets call it lib.dll) that is created from another project (Class Library) that exists in a different solution.
Now, several of the UserControls make calls into lib.dll that return values from the app.config file. At runtime lib.dll works fine and returns the necessary data but at design time, I am getting an exception from lib.dll because the app.config sections are NULL (the exceptions are by design).
Now I could go through each control and wrap any code that calls into lib with
if(!DesignMode) { //code }
But that is a lot of controls to go and apply that to. Is there something I can do globally that would be more elegant then testing the DesignMode property?
Edit
In response to the two comments left below: the solutions provided don't appear to work. The assembly that is causing me a problem lives in the same directory as the app.config. The general directory structure looks like this
References Folder
Configurations (Folder)
appsettings.config
app.config
lib.dll
app.config pulls in several other config files (appsettings, cnx strings, etc) which reside in the Configurations directory. In the case of my exception the value I am trying to get resides in one of these ancillary config files that is referenced by app.config.
This is an interesting question. A solution could be to create in lib.dll a static class like this one :
public static class Config
{
private static readonly _param1;
static Config()
{
_param1 = ConfigurationManager.AppSettings["Param1"] ?? "Your default value";
}
public static string Param1
{
get { return _param1; }
}
}
Then, in your code, insted of writing ConfigurationManager.AppSettings["Param1"], you will use Config.Param1. So you won't need to test the property DesignMode.
There are so many ways to do this, IMHO.
One thought that immedidately comes to mind would be to use an inheritance-based approach for the user controls in question? That way, in the base class, you can put that if (DesignMode) check in, and do the correct branching from there.
// if i were to visualizeyour lib.dll data initializer call like this:
class BaseUserControl
{
// i'm guessing that you initialize the data somehow...
void InitializeData()
{
if (!DesignMode)
{
InitializeDataLocal();
}
}
protected virtual InitializeDataLocal()
{
// whatever base behavior you want should go here.
}
}
// in the derived classes, just put the code you currently have for
// fetching the data from lib.dll here...
class UserControl : BaseUserControl
{
protected override InitializeDataLocal()
{
// fetch from lib.dll...
// optionally invoke some base behavior as well,
// if you need to...
base.InitializeDataLocal();
}
}
I have an integration test LoadFile_DataLoaded_Successfully(). And I want to refactor it to the unit test for breaking dependency with filesytem.
P.S. I am new in TDD:
Here are my production class :
public class LocalizationData
{
private bool IsValidFileName(string fileName)
{
if (fileName.ToLower().EndsWith("xml"))
{
return true;
}
return false;
}
public XmlDataProvider LoadFile(string fileName)
{
if (IsValidFileName(fileName))
{
XmlDataProvider provider =
new XmlDataProvider
{
IsAsynchronous = false,
Source = new Uri(fileName, UriKind.Absolute)
};
return provider;
}
return null;
}
}
and my test class (Nunit)
[TestFixture]
class LocalizationDataTest
{
[Test]
public void LoadFile_DataLoaded_Successfully()
{
var data = new LocalizationData();
string fileName = "d:/azeri.xml";
XmlDataProvider result = data.LoadFile(fileName);
Assert.IsNotNull(result);
Assert.That(result.Document, Is.Not.Null);
}
}
Any idea how to refactor it to break filesystem dependency
What you're missing here is inversion of control. For instance, you can introduce the dependency injection principle into your code:
public interface IXmlDataProviderFactory
{
XmlDataProvider Create(string fileName);
}
public class LocalizationData
{
private IXmlDataProviderFactory factory;
public LocalizationData(IXmlDataProviderFactory factory)
{
this.factory = factory;
}
private bool IsValidFileName(string fileName)
{
return fileName.ToLower().EndsWith("xml");
}
public XmlDataProvider LoadFile(string fileName)
{
if (IsValidFileName(fileName))
{
XmlDataProvider provider = this.factory.Create(fileName);
provider.IsAsynchronous = false;
return provider;
}
return null;
}
}
In the code above the creation of the XmlDataProvider is abstracted away using an IXmlDataProviderFactory interface. An implementation of that interface can be supplied in the constructor of the LocalizationData. You can now write your unit test as follows:
[Test]
public void LoadFile_DataLoaded_Succefully()
{
// Arrange
var expectedProvider = new XmlDataProvider();
string validFileName = CreateValidFileName();
var data = CreateNewLocalizationData(expectedProvider);
// Act
var actualProvider = data.LoadFile(validFileName);
// Assert
Assert.AreEqual(expectedProvider, actualProvider);
}
private static LocalizationData CreateNewLocalizationData(
XmlDataProvider expectedProvider)
{
return new LocalizationData(FakeXmlDataProviderFactory()
{
ProviderToReturn = expectedProvider
});
}
private static string CreateValidFileName()
{
return "d:/azeri.xml";
}
The FakeXmlDataProviderFactory looks like this:
class FakeXmlDataProviderFactory : IXmlDataProviderFactory
{
public XmlDataProvider ProviderToReturn { get; set; }
public XmlDataProvider Create(string fileName)
{
return this.ProviderToReturn;
}
}
Now in your test environment you can (and probably should) always create the class under test manually. However, you want to abstract the creation away in factory methods to prevent you having to change many tests when the class under test changes.
In your production environment however, it can become very cumbersome very soon when you manually have to create the class. Especially when it contains many dependencies. This is where IoC / DI frameworks shine. They can help you with this. For instance, when you want to use the LocalizationData in your production code, you might write code like this:
var localizer = ServiceLocator.Current.GetInstance<LocalizationData>();
var data = data.LoadFile(fileName);
Note that I'm using the Common Service Locator as an example here.
The framework will take care of the creation of that instance for you. Using such a dependency injection framework however, you will have to let the framework know which 'services' your application needs. For instance, when I use the Simple Service Locator library as an example (shameless plug that is), your configuration might look like this:
var container = new SimpleServiceLocator();
container.RegisterSingle<IXmlDataProviderFactory>(
new ProductionXmlDataProviderFactory());
ServiceLocator.SetLocatorProvider(() => container);
This code will usually go in the startup path of your application. Of course the only missing piece of the puzzle is the actual ProductionXmlDataProviderFactory class. Here is it:
class ProductionXmlDataProviderFactory : IXmlDataProviderFactory
{
public XmlDataProvider Create(string fileName)
{
return new XmlDataProvider
{
Source = new Uri(fileName, UriKind.Absolute)
};
}
}
Please also not that you will probably don't want to new up your LocalizationData in your production code yourself, because this class is probably used by other classes that depend on this type. What you would normally do is ask the framework to create the top most class for you (for instance the command that implements a complete use case) and execute it.
I hope this helps.
The problem here is that you are not doing TDD. You wrote the production code first, and now you want to test it.
Erase all that code and start again. Write a test first, and then write the code that passes that test. Then write the next test, etc.
What is your goal? Given a string that ends in "xml" (why not ".xml"?) you want an XML data provider based upon a file whose name is that string. Is that your goal?
The first tests would be the degenerate case. Given a string like "name_with_wrong_ending" your function should fail. How should it fail? Should it return null? Or should it throw an exception? You get to think about this and decide in your test. Then you make the test pass.
Now, what about a string like this: "test_file.xml" but in the case where no such file exists? What do you want the function to do in that case? Should it return null? Should it throw an exception?
The simplest way to test this, of course, is to actually run the code in a directory that does not have that file in it. However, if you'd rather write the test so that it does not use the file system (a wise choice) then you need to be able to ask the question "Does this file exist", and then your test needs to force the answer to be "false".
You can do that by creating a new method in your class named "isFilePresent" or "doesFileExist". Your test can override that function to return 'false'. And now you can test that your 'LoadFile' function works correctly when the file doesn't exist.
Of course now you'll have to test that the normal implementation of "isFilePresent" works correctly. And for that you'll have to use the real file system. However, you can keep file system tests out of your LocalizationData tests by creating a new class named FileSystem and moving your 'isFilePresent' method into that new class. Then your LocalizationData test can create a derivative of that new FileSystem class and override 'isFilePresent' to return false.
You still have to test the regular implementation of FileSystem, but that's in a different set of tests, that only get run once.
OK, what's the next test? What does your 'loadFile' function do when the file does exist, but does not contain valid xml? Should it do anything? Or is that a problem for the client? You decide. But if you decide to check it, you can use the same strategy as before. Make a function named isValidXML and have the test override it to return false.
Finally we need to write the test that actually returns the XMLDataProvider. So the final function that 'loadData' should call, after all those other function is, createXmlDataProvider. And you can override that to return an empty or dummy XmlDataProvider.
Notice that in your tests you have never gone to the real file system and really created an XMLDataProvider based on a file. But what you have done is to check every if statement in your loadData function. You've tested the loadData function.
Now you should write one more test. A test that uses the real file system and a real valid XML file.
When I look at the following code:
public class LocalizationData
{
private static bool IsXML(string fileName)
{
return (fileName != null && fileName.ToLower().EndsWith("xml"));
}
public XmlDataProvider LoadFile(string fileName)
{
if (!IsXML(fileName)) return null*;
return new XmlDataProvider{
IsAsynchronous = false,
Source = new Uri(fileName, UriKind.Absolute)
};
}
}
(* I'm not thrilled about the return null. Yuck! that smells.)
Anyway, I would ask the following questions to myself:
What could possibly break with this code? Are there any complex logic or fragile code that I should safe-guard myself against?
Is there anything complicated to understand or worth highlighting via a test that the code is not able to communicate?
Once I've written this code, how frequently do I think I'll revisit (change) it?
The IsXML function is extremely trivial. Probably does not even belong to this class.
The LoadFile function creates a synchronous XmlDataProvide if it gets a valid XML filename.
I would first search who uses LoadFile and from where fileName is being passed. If its external to our program, then we need some validation. If its internal and somewhere else we are already doing the validation, then we are good to go. As Martin suggested, I would recommend refactoring this to take Uri as the parameter instead of a string.
Once we address that, then all we need to know is if there is any special reason why the XMLDataProvider is in the synchronous mode.
Now, is there anything worth testing? XMLDataProvider is not a class we built, we expect it to work fine when we give a valid Uri.
So frankly, I would not waste my time writing test for this. In the future, if we see more logic creeping in, we might revisit this again.
In one of my (Python) projects, I assume that all unit tests are run in a special directory that contains the folders "data" (input files) and "output" (output files). I'm using a test script that first checks whether those folders exists (i.e. if the current working directory is correct) and then runs the tests. My unit tests can then use relative filenames like "data/test-input.txt".
I don't know how to do this in C#, but maybe you can test for existence of the file "data/azeri.xml" in the test SetUp method.
It has nothing to do with your testing (x), but consider using Uri instead of String as parameter type for your API.
http://msdn.microsoft.com/en-us/library/system.uri(v=VS.100).aspx
x: I think Steven covered that topic pretty very well.
Why do you use the XmlDataProvider? I don't think that it's a valuable unit test, as it stands now. Instead, why don't you test whatever you would do with that data provider?
For example, if you use the XML data to load out a list of Foo objects, make an interface:
public interface IFooLoader
{
IEnumerable<Foo> LoadFromFile(string fileName);
}
You can then test your implementation of this class using a test file you generate during a unit test. In this way you can break your dependency on the filesystem. Delete the file when your test exits (in a finally block).
And as for collaborators that use this type, you can pass in a mock version. You can either hand code the mock, or use a mocking framework such as Moq, Rhino, TypeMock or NMock. Mocking is great, but if you're new to TDD then it's fine to hand code your mocks while you learn what they're useful for. Once you have that, then you are in a good position to understand the good, bad and ugly of mocking frameworks. They can be a bit gnarly to work with when you're starting TDD. Your mileage may vary.
Best of luck.
In this case, you are basically at the lower level of dependency. You are testing that a file exist and that an xmlprovider can be created with the file as source.
The only way that you could break the dependency, would be to inject something to create the XmlDataProvider. You could then mock it to return a XmlDataProvider that you created (as opposed to read). As simplistic example would be:
class XmlDataProviderFactory
{
public virtual XmlDataProvider NewXmlDataProvider(string fileName)
{
return new XmlDataProvider
{
IsAsynchronous = false,
Source = new Uri(fileName, UriKind.Absolute)
};
}
class XmlDataProviderFactoryMock : XmlDataProviderFactory
{
public override XmlDataProvider NewXmlDataProvider(string fileName)
{
return new XmlDataProvider();
}
}
public class LocalizationData
{
...
public XmlDataProvider LoadFile(string fileName, XmlDataProviderFactory factory)
{
if (IsValidFileName(fileName))
{
return factory.NewXmlDataProvider(fileName);
}
return null;
}
}
[TestFixture]
class LocalizationDataTest
{
[Test]
public void LoadFile_DataLoaded_Succefully()
{
var data = new LocalizationData();
string fileName = "d:/azeri.xml";
XmlDataProvider result = data.LoadFile(fileName, new XmlDataProviderFactoryMock());
Assert.IsNotNull(result);
Assert.That(result.Document, Is.Not.Null);
}
}
Using an injection framework could simplify the call to LoadFile by injecting the factory in the class constructor or elsewhere.
I Like #Steven's answer except I think He didn't go far enough:
public interface DataProvider
{
bool IsValidProvider();
void DisableAsynchronousOperation();
}
public class XmlDataProvider : DataProvider
{
private string fName;
private bool asynchronousOperation = true;
public XmlDataProvider(string fileName)
{
fName = fileName;
}
public bool IsValidProvider()
{
return fName.ToLower().EndsWith("xml");
}
public void DisableAsynchronousOperation()
{
asynchronousOperation = false;
}
}
public class LocalizationData
{
private DataProvider dataProvider;
public LocalizationData(DataProvider provider)
{
dataProvider = provider;
}
public DataProvider Load()
{
if (provider.IsValidProvider())
{
provider.DisableAsynchronousOperation();
return provider;
}
return null;
}
}
By not going far enough I mean that he didn't follow the Last Possible Responsible Moment. Push as much down into the implemented DataProvider class as possible.
One thing I didn't do with this code, is drive it with unit tests and mocks. That is why you're still checking the state of the provider to see if it is valid.
Another thing is that I tried to remove the dependencies on having the LocalizationData know that the provider is using a file. What if it was a web service or database?
So first of all let us understand what we need to test. We need to verify that given a valid filename, your LoadFile(fn) method returns an XmlDataProvider, otherwise it returns null.
Why is the LoadFile() method difficult to test ? Because it creates a XmlDataProvider with a URI created from the filename. I have not worked much with C#, but am assuming that if the file does not actually exist on the system, we will get an Exception. The real problem is, your production method LoadFile() is creating something which is difficult to fake. Not being able to fake it is a problem because we cannot ensure the existence of a certain file in all test environments, without having to enforce implicit guidelines.
So the solution is - we should be able to fake the collaborators (XmlDataProvider) of the loadFile method. However, if a method creates it's collaborators it cannot fake them, hence a method should never create it's collaborators.
If a method does not create it's collaborators, how does it get them ? - In one of these two ways:
They should be injected into the method
They should be obtained from some factory
In this case it does not make sense for the XmlDataProvider to be injected into the method, since that is exactly what it is returning. So we should get it from a global Factory - XmlDataProviderFactory.
Here comes the interesting part. When your code is running in production, the factory should return an XmlDataProvider, and when your code is running in a test environment, the factory should return a fake object.
Now the only part of the puzzle is, how to ensure that the factory behaves in different ways in different environments ? One way is to use some properties which have different values in both environments, and the other way is to configure the factory for what it should return. I personally prefer the former way.
Hope this helps.
This time, don't try to break your dependency on the file system. This behavior clearly depends on the file system, and appears to be at the integration point with the file system, so test it with the file system.
Now, I second Bob's advice: throw this code away and try test-driving it. It makes for great practice and is exactly how I trained myself to do it. Good luck.
Instead of returning XmlDataProvider which ties you a specific tech, hide this implementation detail. It looks like you need a repository Role to
LocalizationData GetLocalizationData(params)
You can have an implementation for this Role, which internally uses Xml. You'd need to write integration tests to test whether XmlLocalizationDataRepository can read actual Xml data stores. (Slow).
The rest of your code can mock out GetLocalizationData()
For a little background:
I have a DLL project with the following structure:
Rivworks.Model (project)
\Negotiation (folder)
Model.edmx (model from DB #1)
\NegotiationAutos (folder)
Model.edmx (model from DB #2)
I have moved the connection strings from this project's app.config to the web.config file. They are not in the ConnectionString section. Rather, I have a static class that consumes part of the web.config and exposes them to my app as AppSettings.[settingName].
<FeedAutosEntities_connString>metadata=res://*/;provider=System.Data.SqlClient;provider connection string='Data Source=db4;Initial Catalog=RivFeeds;Persist Security Info=True;User ID=****;Password="****";MultipleActiveResultSets=True'</FeedAutosEntities_connString>
<RivWorkEntities_connString>metadata=res://*/NegotiationAutos.NegotiationAutos.csdl|res://*/NegotiationAutos.NegotiationAutos.ssdl|res://*/NegotiationAutos.NegotiationAutos.msl;provider=System.Data.SqlClient;provider connection string='Data Source=db2;Initial Catalog=RivFramework_Dev;Persist Security Info=True;User ID=****;Password="****";MultipleActiveResultSets=True'</RivWorkEntities_connString>
I have 2 classes, one for each Context and they look like this:
namespace RivWorks.Model
{
public class RivWorksStore
{
private RivWorks.Model.Negotiation.Entities _dbNegotiation;
public RivWorksStore(string connectionString, string metadata, string provider)
{
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.ConnectionString = connectionString;
entityBuilder.Metadata = "res://*/"; // metadata;
//entityBuilder.Provider = provider;
_dbNegotiation = new RivWorks.Model.Negotiation.Entities(entityBuilder.ConnectionString);
}
public RivWorks.Model.Negotiation.Entities NegotiationEntities()
{
return _dbNegotiation;
}
}
}
namespace RivWorks.Model
{
public class FeedStoreReadOnly
{
private RivWorks.Model.NegotiationAutos.Entities _dbFeed;
public FeedStoreReadOnly(string connectionString, string metadata, string provider)
{
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.ConnectionString = connectionString;
entityBuilder.Metadata = "res://*/"; // metadata;
//entityBuilder.Provider = provider;
_dbFeed = new RivWorks.Model.NegotiationAutos.Entities(entityBuilder.ConnectionString);
}
public RivWorks.Model.NegotiationAutos.Entities ReadOnlyEntities()
{
return _dbFeed;
}
}
}
You will note that the MetaData is being rewritten to a short version.
When I comment out that line in each class I get this error:
Unable to load the specified metadata resource.
When I leave that line in in each class I get this error:
Schema specified is not valid. Errors:
Negotiation.Model.csdl(3,4) : error 0019: The EntityContainer name must be unique. An EntityContainer with the name 'Entities' is already defined.
I know it is something simple, something obvious. Any suggestions welcome...
Hijacking this, since it is the top Google result for the error message.
In case anyone else encounters this while only using a single model/context: I once ran into this problem because the assembly containing the model/context was renamed and a copy with the previous name remained in the bin directory of the application. The solution was to delete the old assembly file.
Your two EDMX files probably have the same entity container name. You need to change (at least) one of them.
In the GUI designer, open Model Browser. Look for a node that says "EntityContainer: Entities". Click it. In Properties, change Name to something else. Save and rebuild.
I had the problem too but my solution was to clean the bin directory and then remove the connection string with the entity container name. Then I could rename my entities and put back the connection string.
I renamed my project but the old file was still in the bin folder. I just had to delete the old DLL from the bin folder.
I have found a way to save multiple containers with the same name (namespaced of course).
In EF5 and VS2012 you can set three different namespaces. First you can click on the edmx file in the solution browser and in the properties windows you can set the "Custom Tool Namespace", you can click on the *.Context.tt file right below the edmx and set another namespace there, and finally thanks to a lead from Mr Stuntz awesome answer I realized that by opening the edmx file and clicking in the white space you get another namespace field under Schema in the properties window.
Think we're done, not quite, I know you can see the Entity Container Name field and will try to change the name there but that doesn't seem to work, you get a little error that pops up. Ensure that all your edmx files have an individual namespace there. (I ensured I had a unique namespace in all three places)
Then go to your Model Browser and right click on EntityContainer: Entity to go to properties and change the name of your container(s). From that window with the namespace set everywhere I was able to get multiple contexts with the same name. I was dealing with things like blahcontext and blahcontextcontainer all of a sudden even though they were in different folders.
When you see that its a namespace problem. Or lack thereof.
In my case, the problem was caused by my connection string in Web.config being named the same thing as my entities container class.
Change
<add name="ConflictingNameEntities" connectionString="metadata=res://*/blahblah
to
<add name="ConflictingNameEntitiesConnection" connectionString="metadata=res://*/blahblah
and regenerate the container class by right-clicking ConflictingNameModel.Context.tt in Solution Explorer and clicking "Run Custom Tool".
I just ran into this. It looks like somehow Entity Framework got into a bad state in terms of what tables it thought it needed to add.
Normally EF will not recognize that a new table has to be created until you put the line
public virtual DbSet<NewTable> NewTable { get; set; }
inside your context class.
However, EF somehow got into a bad state where the mere presence of the NewTable class in my solution was triggering it to think that it needed to generate that table. So by the time the above line in the context triggered it to create a NewTable table, it already thought it had done it, hence the error about duplicate entities.
I just removed the NewTable class from my solution, commented things out so it would compile again (thankfully there wasn't too much of this), then added a new migration to make sure it was blank as it should have been. Then once things were back into a more predictable state, I re-added the NewTable class back into the solution and adding the migration worked fine.
If you are using web deployment from Visual Studio sometimes doesn't delete the old dlls. I had the same problem, change to Web Deployment Package and didn't give me problems.
I had a same problem in my asp.net website, to resolve the problem I purposely added compile time error in one of the cs file in the app code by removing a semicolon, then I rectified the compilation problem by adding semicolon again.
This process caused application to compile again.After this error got vanished.
The other cause of this problem, your add model in any solution project and change your model project.
--PROJECT A --> MODEL.EDMX
--- WEB CONFIG -->Entity Connection
--PROJECT B
--- WEB CONFIG -->Entity Connection
Later, I think this structure is bad and Change project.
--PROJECT A
using PROJECT.C;
WEB.CONFIG - USE PROJECT C APP.CONFIG CONNECTIONSTRING
--PROJECT B
using PROJECT.C;
WEB.CONFIG - USE PROJECT C APP.CONFIG CONNECTIONSTRING
--PROJECT C (CLASS LIBRARY) --> MODEL.EDMX
--- APP.CONFIG -->Entity Connection
Everything was fine but I get an error.
Error Detail : The EntityContainer name must be unique. An EntityContainer with the name 'Entities' is already defined
Because I forgot change Web.Config files.
OLD WEB.CONFIG
<add name="donatelloEntities" connectionString="metadata=res://*;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=donatello;persist security info=True;user id=1;password=1;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
NEW WEB.CONFIG
<add name="donatelloEntities" connectionString="metadata=res://*/EntityModel.Model.csdl|res://*/EntityModel.Model.ssdl|res://*/EntityModel.Model.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=donatello;user id=sa;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
This Problem is Simple but may cause loss of time. I wanted to give an example. I hope is useful.
Thanks.
To solve the issue Entity 6.2.0, VS 2017, single edmx
I changed the name of my model.edmx to another name, built the project, then changed it back to the original name.
In my case, probably after merging a version back, my startup project file (csproj) got corrupted.
Al the Entity classes where added:
<Compile Include="Class.cs">
<DependentUpon>MyModel.tt</DependentUpon>
</Compile>
After removing all relevant entries by hand the problem was solved.
Strange problems have strange answers, so please do not blame.
first, take a quick look at this part of code
I got a problem the problem
The EntityContainer name must be unique. An EntityContainer with the name 'Entities' is already defined
with this class name 'ShippingSpeed_Month_Speed'
The solution for me was just renaming 'speeds' to 'speedsx'.
So, you MAY need to rename something like the ending name of the relation or navigational property which is the same ending of the same table name or the ending name of the DbSet<>
I'm answering to document what worked for me and hoping to benefit others.
Thanks
No bin, just aspx/edmx ? Just move the shema files (mode.edmx + model.designer.vb) refresh and put them back ! IIS/aspnet probably corrupt for x reason.