I'm getting the following exception:
The number of members in the
conceptual type 'MyModel.Customer'
does not match with the number of
members on the object side type
'MyNamespace.Customer'. Make sure the
number of members are the same.
In the following code:
public CusomserService
{
// ...
public IEnumerable<Customer> GetCustomers()
{
return new Repository<Customer>().All();
}
}
public class Repository<T>() where T : EntityObject
{
// ...
public IQueryable<T> All()
{
return _context.CreateObjectSet<T>().AsQueryable<T>(); /* HERE THE EXCEPTION IS THROWN */
}
}
The generics repository was working fine until I made some changes in my EF Model. I'm letting EF create the database (through Generate database from Model option).
Where do I start?
EDIT: I've solved it.
The problem had nothing to do with EF or my model. I had renamed the data layer project (and it's assembly name) from original_name.dll to new_name.dll. I had updated the service layer project reference to the data layer project, but the the old assembly (original_name.dll) was still in the bin directory. Deleting the old assembly from the service layer's bin directory and rebuilding the solution solved the problem.
It seems that Classes 'MyModel.Customer' does not match with each other 'MyNamespace.Customer'.
Try right clicking on the edmx file and selecting Run Custom Tool
or right click on edmx in solution explorer and open with xml and verify your recent changes.
Related
Okay this is driving me crazy. I got one almost finished project (which works perfectly) and I wanted to make another one in the same way. The thing is there is a solution with two layers DataAccessLayer and BusinessLogicLayer. Both of these layers have a Model library with all models in the project. I need to convert the model from the first layer to a model of a second layer in the manager library. This works in the finished project I received but I can not manage to make it on mine.
The thing is I can't make the necessary references to work like they do on the finished project. The structure is:
BusinessLogicLayer
--Managers
----Users
--Models
----User
DataAccessLayer
--Models
----User
In the Managers project I have a reference added to DataAccessLayer.Models.
And inside the Users class I got:
using Library.BusinessLogicLayer.Models;
Now in my project this line is red underlined:
Error CS0234 The type or namespace name 'Models' does not exist in the
namespace 'Library.BusinessLogicLayer' (are you missing an assembly
reference?)
I am not even sure how and why this works on that original project. But I can't figure it out so it's working right on my project and the structure is the exact same. Anyone have an idea about this?
EDIT:
Dunno why I didn't upload this earlier. Here is the structure.
https://i.imgur.com/srnySFJ.jpg
EDIT2:
Since it is not quite understandable I uploaded the whole project on github so you can take a closer look at it.
https://github.com/Morsusy2k/Library
And here is the problem:
https://i.imgur.com/DvCvnMA.jpg
From what you described above and from my understanding, it seems that Managers and Models are two different projects. If that is the case, make sure that you add a reference to BusinessLogicLayer.Models in your BusinessLogicLayer.Managers.
If, on the other hand, you have only two projects BusinessLogicLayer and DataAccessLayer then it could very well mean that Library.BusinessLogicLayer.Models is not the name of the namespace.
UPDATE
From the picture that you added, you might need to add a reference to Library.BusinessLogicLayer.Models.Models. You have a folder named Models and a project named Models. Visual Studio automatically generates namespaces based on the Solution name, Solution folders, project name, folders within project.
There were three issues with your code. The first one is that you are supposed to add a reference to Library.DataAccessLayer.Models and not to Library.BusinessLogicLayer.Models. This is due to the fact that you have User in DataAccessLayer.Models and User2 in BusinessLogicLayer.Models.
The other two issues were with the Map method where you are sending incorrect number of arguments to the constructor (you are missing UserId) and the other issues is with your DateOfBirth and DateJoined being in the wrong order in the same method.
using System;
using System.Collections.Generic;
using System.Linq;
using global::Library.BusinessLogicLayer.Models;
using Library.BusinessLogicLayer.Managers.Properties;
using Library.DataAccessLayer.Models; // <-- Add reference to this
namespace Library.BusinessLogicLayer.Managers
{
public class Users2
{
public IEnumerable<User> GetAll()
{
using(DataAccessLayer.DBAccess.Library library = new DataAccessLayer.DBAccess.Library(Settings.Default.LibraryDbConnection))
{
return library.Users.GetAll().Select(user => Map(user));
}
}
private User Map(DataAccessLayer.Models.User dbUser)
{
if (dbUser == null)
return null;
// TODO: Constructor is missing a paremeter. I'll add a temporary one
int tempUserId = 0;
User user = new User(tempUserId, dbUser.Name, dbUser.UserName, dbUser.Password, dbUser.Email, dbUser.DateJoined, dbUser.DateOfBirth) // <-- The last two params are in the wrong order
{
Id = dbUser.Id
};
return user;
}
private Library.DataAccessLayer.Models.User Map(User2 user)
{
if (user == null)
throw new ArgumentNullException("user","Valid user is mandatory!");
return new DataAccessLayer.Models.User(user.Id,user.Name, user.UserName, user.Password, user.Email, user.DateJoined, user.DateOfBirth);
}
}
}
Also, regarding the last screenshot that you provided, you do not have Library.BusinessLogicLayer.Models2 namespace. Remove number 2 to get it to work.
As I don't have permission to update your repo with the fixed code, you'll have to fix it manually based on my answer. Otherwise, let me know so that we see how I can push the code back.
There are a few things you could try:
This error could be appearing within BusinessLogicLayer because DataAccessLayer failed to build. Try building DataAccessLayer by itself to see if you get a different error.
The references might be "added", but you might not be referencing the correct DLL or version for some reason. Check your .csproj files manually to ensure all references and versions are correct, have the right hint paths, etc. If you have any config files, you should also review them to ensure there are no version conflicts.
In addition to checking the references, it is possible to add if-then and switch case logic inside of the .csproj files. This is an MSBuild feature that Visual Studio doesn't support through its GUI, so you may need to copy/update this logic manually in your current .csproj files if any existed.
Check your default namespaces in project properties to see if they are the same as your old project. If you added new files since you moved to this project, they may have been inadvertently added with the wrong namespace and that namespace may be causing a conflict. You could also try using global::Library.BusinessLogicLayer.Models; to see if that fixes or changes the error message or at least if Intellisense is picking the namespace up.
If that doesn't work, review all of your namespaces in all .cs files to see if you have any that have gone rogue.
Since your Models namespace has the problem and you have 2 of them with the same name, try temporarily renaming one of them (yes, every .cs file in one of the projects) to Models2 to see if it provides a clue (such as the error going away or changing).
Be gentle, its only an illusion that it looks like a duplicate, but different circumstances ;)
I have a solution with three separate projects, the main project and a BLL and a DAL project (n-tier). In the DAL I have generated Linq To SQL classes from an existing database, as well as a class that has all the crud operations, and another class for custom data classes.
The main project references the BLL and the BLL references the DAL.
In the main project I am populating a grid from a method in the BLL that calls the method from the DAL and that returns a list. I have stepped through the code and I keep getting the error.
Object reference not set to an instance of an object.
and it brings me to this method in my designer of the Linq To SQL classes (.dbml)
public BasicInventoryDBDataContext() :
base(global::System.Configuration.ConfigurationManager.ConnectionStrings["BasicInventoryConnectionString"].ConnectionString, mappingSource)
When I try and databind to a grid.
I have looked in my webconfig for the DAL project and it seems legit because the connection string is in there.
I have looked around on SO and have seen similar questions to this error, but none pertaining (that I have found) when the DAL is in a separate project, let alone when using Linq To SQL.
I have tried, deleting the DAL and BLL projects and recreating them ( Not a big deal since, I have just started the project, and its in its infancy ). I haven't had this issue when I have the Linq To SQL classes in the same project.
Any idea's?
EDIT
Here is the page I am using to make sure things are working before continuing.
#region Initialization
public BasicInventoryDAL bl = new BasicInventoryDAL();
#endregion
protected void Page_Load(object sender, EventArgs e)
{
rgVendor.DataSource = bl.GetVendorBrowse();
rgVendor.DataBind();
}
I have put a break of initialization of BasicInventoryDAL, and when I step through, its brings me to the DAL Project
public class BasicInventoryDAL
{
#region Initialization
public BasicInventoryDBDataContext dc = new BasicInventoryDBDataContext();
#endregion
public List<VendorBrowse> GetVendorBrowse()
{
List<VendorBrowse> lst = new List<VendorBrowse>();
var queryGetVendorBrowse = from f in dc.vw_Vendor_Browses
select f;
foreach (var v in queryGetVendorBrowse)
lst.Add(new VendorBrowse
{
VendorID = v.VendorID,
VendorName = v.VendorName,
City = v.City,
Country = v.Country
});
return lst;
}
}
As soon as it gets to the public BasicInventoryDBDataContext dc = new BasicInventoryDBDataContext(); That's when the error gets thrown.
Here is the connection string in my web config
<connectionStrings>
<add name="BasicInventoryConnectionString" connectionString="Data Source=HERBERT\SQLEXPRESS;Initial Catalog=BasicInventory;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
The NullReferenceException was thrown because the connection string was defined in the wrong config file. The generated code assumed that the connection string was available. That was a bad assumption, even if it was Microsoft making the bad assumption.
Since Day 1, .NET configuration has always been in the config file associated with the executable code. In the case of ASP.NET, it needs to be in the web.config files associated with the web application. In the case of a .EXE, it has to be in programname.exe.config.
I'm getting designer error on code:
The Component i'm willing to define a List of properties for:
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
namespace TestProjectForProperty.Test
{
public class MyTreeView : TreeView
{
private List<TypeDescriptorBase> _descriptorsAvailable = new List<TypeDescriptorBase>();
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public List<TypeDescriptorBase> DescriptorsAvailable
{
get { return _descriptorsAvailable; }
set { _descriptorsAvailable = value; }
}
}
}
The Descriptor itself:
using System;
namespace TestProjectForProperty.Test
{
[Serializable]
public class TypeDescriptorBase
{
public string Name { get; set; }
public override string ToString()
{
return Name;
}
}
}
I am getting the following error if i try to use the component for example on a form and add any items on the property sheet or in the component's constructor to the DescriptorsAvailable property
Error 1 Invalid Resx file. Could not load type
System.Collections.Generic.List`1[[TestProjectForProperty.Test.TypeDescriptorBase,
TestProjectForProperty, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null]], mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089 which is used in the .RESX file.
Ensure that the necessary references have been added to your project.
Line 134, position 5. ...\visual studio
2010\Projects\TestProjectForProperty\TestProjectForProperty\Form1.resx 134 5 TestProjectForProperty
In the Resx file there is data field with base64 encoded stuff inside when this error is present.
I have been searching for an answer, but the best i got is to restart everything, it didn't help me, do you guys have any suggestions? I'm using .net 4 client and visual studio 2010
In my experience, this is due to a change of version of a referenced library, or a change of the lib itself, which contains the backing type of a property you have defined in your user control. The solution is to "force" the visual studio designer to re-initialize it's designer code for that type, and not expect to retrieve a "canned" version of it from the .resx file of the control.
1) Delete the offending data section in the .resx file of your control. This will be a section in the xml of the .resx file associated with your user control, which has a node: <data></data> - the name attribute will be set to whatever you've named that object in the properties of whatever you added this type to. The <data>/data> section contains a base64 encoded string that is the encoded form of the name and version of the library the type comes from. This is where the problem ism, because it now contains an encoded version of the library and/or version number you are no longer referencing in order to include the type. Delete the entire <data>/data> section, from opening to closing tag, save the change and close the file. Now the "artifact" is gone.
2) Now find the place in the designer file for your control, where the type is instantiated; this is initialization code generated for you by visual studio, and it is the place that is expecting to load a "canned" definition of the type from the base64 encoded string contained within the .resx file. The line will look something like this:
this.myCtrlFoo.MyPropertyFroo = ((MyNamespaceFoo.MyTypeFoo)(resources.GetObject("myCtrlFoo.MyPropertyFroo")));
...now just replace the resources.GetObjec call with the instantiation of a new instance of the appropriate type like so:
this.myCtrlFoo.MyPropertyFroo = ((MyNamespaceFoo.MyTypeFoo)(new MyNamespaceFoo.MyTypeFoo()));
...now save the change to the file, close it, rebuild, and everything should now build & run OK.
Put the MyTreeView and TypeDescriptorBase classes into another project and reference it from your GUI project will resolve the issues.
I'm not sure why exactly the problem occurs - I guess it has something to do with the way the serializing process is generating the base64 string for the DescriptorsAvailable Property. Maybe somebody else can give us some insight.
I've struggled quite a bit with this; I have three user controls that all expose the same non-designer property, but for some reason, any change to two of the three would instantly cause the next build to fail with this same issue. This is in VS 2015.
I wound up having to add the following two attributes to the property that kept expanding in the resx file, and it hasn't occurred since. It works for me because they're not available in the designer anyway.
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
For me, this error occured when I used a custom class as a property for the user control. When I switched from property to traditional get- and set- methods, the error disappeared. I guess this is because properties are already compiled at design-time, so when you build the whole project, a new version of the custom class is compiled which is separate from the one of the control, and the reference is broken.
For me, with the custom class Inventory, all I had to do was to switch from this property-based approach:
public Inventory Resources {get;set;}
to this method-based approach:
private Inventory resources;
public Inventory getResources() { return resources; }
public void setResources(Inventory newResources) { resources = newResources; }
I hope this helps someone, as I've been spending some hours on figuring it out.
In my case I've got the error : "error MSB3103: Invalid Resx file. The specified module could not be found" executed in a light windows container based on mcr.microsoft.com/powershell instead of mcr.microsoft.com/windows:1909 (was working fine on 1909).
The error was on a ressource icon that was compressed with PNG inside.
It can be checked by opening the ressource on visual studio : Project > Properties > Ressources.resx, select icons, double click on the icon, check the end of the title that is either "..,BMP]" or "...,PNG]").
Updating the icon with an uncompressed format solve the "Invalid Resx file" issue.
I stumbled across this question today whilst looking for the solution to a similar issue.
Unfortunately none of the above worked for me, however my issue turned out to be that I had different versions of the .NET Framework for different projects. For example;
Project A - .NET Framework 4.7.2
Project B - .NET Framework 4
Where Project B was referencing Project A. Solution was simply to change the .NET Framework version of Project B to 4.7.2 (in my case) and hey presto the issue was resolved.
A shame Visual Studio doesn't provide a more helpful error message in this case, but something to look out for!
So here is my issue. I have a complex archetecture of interfaces and abstract classes that I am trying to load up via Assembly.LoadFrom("x.dll"). When certain types that have an interface implementation where the implementation is explicit in a base class are trying to be loaded, I am getting a TypeLoadException saying:
Method 'MyMethod' in type 'MyPart2DerivedType' from assembly 'MyPart2Assembly, version...' does not have an implementation. I am trying to understand why this is as I have gone through several articles and have even attempted to delete the obj files and dlls manually. Here are the references to what I have done so far:
Solution to TypeLoadException
TypeLoadException says 'no implementation', but it is implemented
Visual Studio Forumns: TypeLoadException
Private accessors and explicit interface implementation
So here is my example code:
//This is in project 1
public interface IFooPart1
{
void DoStuff();
}
//This is in project 2
public interface IFooPart2
{
void DoOtherStuff();
}
//This is in project 3
public interface IFooPart3: IFooPart1, IFooPart2
{
void DoEvenMoreStuff();
}
//This is in project 4
public abstract class MyBaseType: IFooPart1, IFooPart2
{
void IFooPart1.DoStuff()
{
DoStuffInternal();
}
void IFooPart2.DoOtherStuff()
{
DoOtherStuffInternal();
}
}
//This is in project 5
public class MyDerivedType: MyBaseType, IFooPart3
{
public void DoEvenMoreStuff()
{
//Logic here...
}
}
//Only has references to projects 1, 2, & 3 (only interfaces)
public class Program
{
void Main(params string[] args)
{
//Get the path to the actual dll
string assemblyDll = args[0];
//Gets the class name to load (full name, eg: MyNameSpace.MyDerivedType)
string classNameToLoad = args[1];
//This part works...
var fooAssembly = Assembly.LoadFrom(assemblyDll);
//Here we throw a TypeLoadException stating
// Method 'DoStuff' in type 'MyDerivedType' from assembly 'Project 5...' does
// not have an implementation.
Type myDerivedTypeExpected = Assembly.GetType(classNameToLoad);
}
}
Note: If I move the explicit implementation to MyDerivedType instead of MyBaseType it works... but I don't get why I would have to do that. Seems like I should be able to. This code is only an example, the actual code has a factory that returns the loaded class but only via the interface type. (eg: var myDerivedType = GetInstance();)
Okay for everyone that is interested in my stupid fix. Here was my problem:
Project6 (which was the console app) has PROJECT references to the other projects, not references to the dlls in the location that they are supposed to build to. The other projects actually were being built to a specific repository area. So, the console application was using it's own version of the dll's when it was trying to automatically load the dependancies. This evidently made some other type way down there that was being dynamically loaded to not be loaded because it was not in the same folder as the dlls that were there...
So in short, Assembly.LoadFrom might cause you to load an assembly twice, but .NET treats it like a different assembly!!! This may introduce some real odd errors when trying to dynamically load types!!!
Please learn from my frustration/mistake. Fiends don't let freinds DI alone (code review is key to catching this stupid stuff).
I've had a similar problem caused by one of my projects having a reference to an older version of a nuget package dependency. The older version didn't have an implementation for one of the methods.
I have been trying to find the answer to this simple question - but so far couldn't figure it out.
Let say I have MyDb.sqlproj, with various sql content (sprocs, views, trigger, etc).
I have added a new UDF through Add-> New item -> SQL CLR C#, User Defined Function.
For example:
namespace MyNameSpace
{
public class MyClass
{
[SqlFunction(DataAccess = DataAccessKind.Read)]
//I use different attributes here, but it doesn't matter
public static int Method1()
{
return 0;
}
}
}
In MyDb.sqlproj Properties, SQLCLR tab MyDb is the name of assembly and default namespace
In my sql code I call the clr method using EXTERNAL NAME:
CREATE PROCEDURE ClrMethod1
RETURNS [int] WITH EXECUTE AS CALLER
AS EXTERNAL NAME [MyDb].[MyNamespace.MyClass].[Method1]
I seem to tried everything to get the last line to compile. It cannot resolve the reference and get:
SQL71501: Function: [name of my sql function] has an unresolved
reference to Assembly [MyDb]
Please point me to the right way to get it working. What could I be missing?
I am using VS2010 SP1 and latest version of SSDT
You must add your compiled DLL containing your CLR code as a Reference. So under your MyDb SSDT project->References(right click)->Add Reference, browse to the DLL.
You could probably get away with referencing the project instead of the DLL if you had the CLR(class library) project in the same solution, but in my case I am referencing a DLL(compiled for a seperate solution).
As far as the format of the AS EXTERNAL NAME line:
AS EXTERNAL NAME [AssemblyName].[ClassName].[FunctionName]
Note: For CLR objects I remove the namespaces from around my classes/code just to simplify things, because this step is usually the most problematic. It is easy to confuse the AssmeblyName/DLL Name/Namespace. The AssemblyName is found in your CLR class library project by accessing the Project Properties->Application->"Assembly Name:". I would remove any non alpha-numeric/spaces from it just to simplify the name and rule out that as a problem.
So I would try that, and once you get that working, if you really want namespaces, then you can add the namespace and figure out the syntax from there, and at least you know the other parts are correct.
Ok reallized that you have a *.cs file actually inside the same SSDT project. so in that case if your code is this:
CS file:
public partial class UserDefinedFunctions
{
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString SqlFunction1()
{
// Put your code here
return new SqlString (string.Empty);
}
}
SQL file:
CREATE PROCEDURE ClrMethod1
RETURNS [int] WITH EXECUTE AS CALLER
AS EXTERNAL NAME [MyDB].[UserDefinedFunctions].[SqlFunction1]
This compiles for me. Note: Again no namespace was used. When I did Add New Item... the generated code did not come with a namespace.