Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The type X conflicts with imported type X

In Entity Framework (Database first) I am trying to add some Data annotations to created classes.

In general: I have class X created:

namespace Info
{
    using System;
    using System.Collections.Generic;

    public partial class X
    {
        public string SomeProperty {get; set;}
        ...
    }
}

I want to property SomeProperty to be ignored when serializing to JSON thus in App_Code/Metadata I create class X.cs and I add some MetaData:

namespace Info
{

    public class XMetaData
    {
        [JsonIgnore]
        public string SomeProperty{get; set;}
    }

     [MetadataType(typeof(XMetaData))]
     public partial class X
     {

     }

}

Above I've manually changed namespace from Info.App_Code.Metadata to Info to have partial classes matched.

However in all places where I use X class i have warning

The type Info.X in '.../Info/App_Code/Metadata/X.cs ' conflicts with the imported type Info.X in '.../Info/X.cs'. Using the type defined in '.../Info/App_Code/Metadata/X.cs '

I expected that both partial classes would be merged however all occurrences are referring to that empty one X class.

Does anybody know what I am missing?

like image 697
el vis Avatar asked Jul 04 '13 12:07

el vis


1 Answers

Multiple partial class definitions that refer to the same class must all exist within a single assembly. In your example above during compilation the meta-data should be baked into the class and after compilation the class is whole, comprising of all the parts. Partial classes are a means to split the definition of the same class into multiple files.

See here for an exhaustive explanation but note the following:

All partial-type definitions meant to be parts of the same type must be defined in the same assembly and the same module (.exe or .dll file). Partial definitions cannot span multiple modules.

This link here explains that

In general, ASP.NET creates an assembly for each application directory (such as App_Code) and one for the main directory.

For your case, although the partial classes are in the same project and the same namespace they are not being compiled into the same assembly.

like image 113
qujck Avatar answered Sep 23 '22 22:09

qujck