locked
possible bug with Inheritance and NotMapped RRS feed

  • Question

  • Ok the following is giving me an  error with EF 5 pre release on Visual Studio 2011 , was working with 4.3. 

    "You cannot use Ignore method on the property 'EffectName' on type 'L6.Model.ModuleSkillEffectHolder' because this type inherits from the type 'L6.Model.ModuleEffectHolder' where this property is mapped. To exclude this property from your model, use NotMappedAttribute or Ignore method on the base type."  

    Am i doing something wrong  , is it a bug or is tehre a work around ?

     code block is not working.  

     public partial class ModuleEffectHolder : IIdentifier
        {
            public ModuleEffectHolder()
            {
                //            MaxLevel = 1000;
                NLevel = 1;
                EffectValue = 1;
                ModuleEffect = new EffectNone();
            }

            [Key]
            public int Id { get; set; }

           public ModuleEffect ModuleEffect { get; set; }


            public float EffectValue { get; set; } 

           //TODO remove
            public int ParentId { get; set; }

            //HACK   UI  viewmodel should flatten
            [NotMapped]
           public string EffectName { get { return ModuleEffect.EffectName; } set { foreach (var eff in ModuleEffect.Effects) if (eff.EffectName == value) ModuleEffect = eff; } }
        }

       public partial class ModuleBuildingEffectHolder : ModuleEffectHolder

       {
            virtual public int? BuildingTypeId { get; set; }
            virtual public ModuleBuildingType BuildingType { get; set; }
        }

     public partial class ModuleEffect
        {

            public ModuleEffect()
            {
                EffectName = this.GetType().Name.Replace("Module" , string.Empty).Replace("Effect" , string.Empty); 
            }
            
            //HACK for inheritance 
            public int Id { get; set; }
            
            public string EffectName { get; set; }  //Fire description...
            //public string ModuleEffectType { get; set; }  //Fire description...
        }


        //dummy
        public partial class EffectNone : ModuleEffect
        {
        }

    Wednesday, March 14, 2012 11:53 AM

Answers

  • Hi Benk3,

    Welcome!

    -----------------------------------------------------------------------------------------
                  Known Issues with Entity Framework 4.x and .NET Framework 4.5           
    -----------------------------------------------------------------------------------------

    Entity Framework 4.1 thru 4.3 included additional data annotations in the
    System.ComponentModel.DataAnnotations namespace in the EntityFramework assembly.
    In .NET 4.5 these annotations were moved to be part of the .NET Framework in the
    System.ComponentModel.DataAnnotations.Schema namespace of the
    System.ComponentModel.DataAnnotations.dll assembly. If you are using EF 4.x and targeting
    .NET 4.5 this results in two data annotations with the same name in different assemblies.
    Because the annotations in the .NET Framework are in a different namespace we were not
    able to use type forwarding to avoid this conflict.

    It is possible to use EF 4.x on .NET 4.5 but we recommend using the latest pre-release
    version of EF 5. If you are not using the affected data annotations there is no impact
    on your code. If you are using the data annotations in a C# project you can use the extern
    modifier to ensure your code uses the annotations from EntityFramework.dll
    (http://msdn.microsoft.com/en-us/library/e59b22c5(v=VS.80).aspx). If you use the new
    annotations from the System.ComponentModel.DataAnnotations.dll assembly in .NET 4.5
    they will not be processed by Code First.

    The affected annotations are:
    - Column
    - ComplexType
    - DatabaseGenerated
    - DatabaseGeneratedOption
    - ForeignKey
    - InverseProperty
    - MaxLength
    - MinLength
    - NotMapped
    - Table

    Have a nice day.


    Alan Chen[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by Alan_chen Monday, March 26, 2012 1:40 AM
    Thursday, March 15, 2012 6:06 AM

All replies

  • Hi Benk3,

    Welcome!

    -----------------------------------------------------------------------------------------
                  Known Issues with Entity Framework 4.x and .NET Framework 4.5           
    -----------------------------------------------------------------------------------------

    Entity Framework 4.1 thru 4.3 included additional data annotations in the
    System.ComponentModel.DataAnnotations namespace in the EntityFramework assembly.
    In .NET 4.5 these annotations were moved to be part of the .NET Framework in the
    System.ComponentModel.DataAnnotations.Schema namespace of the
    System.ComponentModel.DataAnnotations.dll assembly. If you are using EF 4.x and targeting
    .NET 4.5 this results in two data annotations with the same name in different assemblies.
    Because the annotations in the .NET Framework are in a different namespace we were not
    able to use type forwarding to avoid this conflict.

    It is possible to use EF 4.x on .NET 4.5 but we recommend using the latest pre-release
    version of EF 5. If you are not using the affected data annotations there is no impact
    on your code. If you are using the data annotations in a C# project you can use the extern
    modifier to ensure your code uses the annotations from EntityFramework.dll
    (http://msdn.microsoft.com/en-us/library/e59b22c5(v=VS.80).aspx). If you use the new
    annotations from the System.ComponentModel.DataAnnotations.dll assembly in .NET 4.5
    they will not be processed by Code First.

    The affected annotations are:
    - Column
    - ComplexType
    - DatabaseGenerated
    - DatabaseGeneratedOption
    - ForeignKey
    - InverseProperty
    - MaxLength
    - MinLength
    - NotMapped
    - Table

    Have a nice day.


    Alan Chen[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by Alan_chen Monday, March 26, 2012 1:40 AM
    Thursday, March 15, 2012 6:06 AM
  • I'm having this problem, too. 

    I am not using EF4.  I'm using .NET 4.5 and EF5 with VS2012 beta.

    The description of the solution is not clear -- My code is using the NotMappedAttribute from System.ComponentModel.DataAnnotations.dll (v4.0.0.0) but I still get the error when code first builds the model.

    public class CalendarEntry {
        // ... stuff ...
    
        [NotMapped]
        public DateTime EndTime { get; set; }
    
    }
    
    public class SpecificCalendarEntry : CalendarEntry {
        // ... more stuff ... 
    }

    I get the following exception:

    You cannot use Ignore method on the property 'EndTime' on type 'BackStage.Domain.Entities.SpecificCalendarEntry' because this type inherits from the type 'BackStage.Domain.Entities.CalendarEntry' where this property is mapped. To exclude this property from your model, use NotMappedAttribute or Ignore method on the base type.

    -- pryankster

    Friday, April 13, 2012 12:20 AM
  • Hi Alan,

    I am getting exactly the same error in exactly the same scenario as 'pryankster'.

    Your answer seems to combine two separate scenarios and this is making it difficult to understand.

    I am using .NET 4.5 with EF 5.0 beta.

    If I understand your answer, you are suggesting that my code is using the 'NotMapped' class from .NET 4.5 instead of the class provided by EF 5.0 beta.

    Is that a correct assumption?

    If so, shouldn't the compile fail with an ambiguous class name error?

    Saturday, April 14, 2012 6:33 AM
  • I've just upgraded my solution from EF4.1 + .NET4 to using EF5 RC + .NET4.5 and have started getting this error as well using the following basic console app code:

    Imports System.ComponentModel.DataAnnotations.Schema
    Imports System.Data.Entity
    
    Public MustInherit Class ModelBase
    
        Public Property Id As Integer
        <NotMapped()> _
        Public Property AintMapped As Boolean
    
    End Class
    
    Public MustInherit Class Animal
        Inherits ModelBase
    End Class
    
    Public Class AnimalDog
        Inherits Animal
    
        Public Overridable Property CaughtBy As DogCatcher
    
    End Class
    
    Public Class DogCatcher
        Inherits ModelBase
    
        Public Overridable Property DogsCaught As List(Of AnimalDog)
    
    End Class
    
    <DbModelBuilderVersion(DbModelBuilderVersion.V5_0)> _
    Public Class MyContext
        Inherits DbContext
    
        Public Property DogCatchers() As DbSet(Of DogCatcher)
        Public Property Animals() As DbSet(Of Animal)
    
    End Class
    
    Module Main
    
        Sub Main()
            Dim context As New MyContext
            context.DogCatchers.Add(New DogCatcher)
        End Sub
    
    End Module

    So, this bug must still exist in EF5. Anyone know of any workarounds until its fixed (other than rolling back to EF4.1 + .NET4)?





    Wednesday, June 6, 2012 8:12 AM
  • I've tried removing the NotMapped attribute and instead using 'Ignore' on the 'ModelBase.AintMapped' property in the fluent api mappings. Although this gets rid of the above error, it prevents the property from being ignored for some reason as EF generates queries with the property included. These queries fail of course as that property has no column in the db (the reason for needing to ignore it in the first place).

    As Marc mentioned previously, the answer given by Allan does not make it clear if this is supposed to work in EF5 or not. Can anyone clarify this further?

    Friday, June 8, 2012 6:34 AM
  • Ok, there's definitely something strange going on with this.

    I reverted back to the code I posted above that uses the NotMapped attribute, but for fun I swapped these lines:

    Public Property DogCatchers() As DbSet(Of DogCatcher)
    Public Property Animals() As DbSet(Of Animal)

    ...to become:

    Public Property Animals() As DbSet(Of Animal)
    Public Property DogCatchers() As DbSet(Of DogCatcher)

    For some weird reason this makes it stop throwing the error and it works. So, somehow the order that the DbSet's are declared in the context affects this, which seems like a bug to me.



    Friday, June 8, 2012 7:39 AM
  • I'm also bothered by this. I'm using EF 5.0 prerrelease and targeting .NET 4.0.

    What's wrong with this?


    Desde España / From Spain

    Sunday, July 22, 2012 8:38 AM
  • I had a look in the EF6 beta code for this bug and discovered that if you replace the following line from the System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.LiftDeclaredProperties method:

    BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))

    with:

    BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly))

    it stops the annoying exception being raised and all seems to work ok.

    Although, given I don't fully understand what this LiftDeclaredProperties method is trying to do, I'm not 100% sure if this is a correct fix.

    • Proposed as answer by Shane Hancock Tuesday, July 24, 2012 9:31 AM
    • Unproposed as answer by Shane Hancock Tuesday, July 24, 2012 9:31 AM
    Tuesday, July 24, 2012 9:30 AM
  • I have the exact same Problem with EF5 (Final) with .Net 4.0. I recognized different Error Messages while changing the Order of DbSet Declarations in the Context. Is it possible to download the Source of the Entity Framework 5.0 (Final) to fix the error by changing the above line (as Shane Hancock did)?

    Can someone give me a link to that Source? I could only find Source of the 6.0beta.

    best regards,

    Chris

    • Proposed as answer by mjgade Wednesday, August 29, 2012 2:23 PM
    • Unproposed as answer by mjgade Wednesday, August 29, 2012 2:23 PM
    Tuesday, August 28, 2012 6:46 AM
  • These behavior we got with another exception in EF4.0 too. Can't remember the exact Scenario, but there is an Post in this Forums to this Problem too.

    In our Project you can still find the warning message ;)

    //// ########################################################################################## //// //// DON'T EVEN THINK ABOUT DELETING OR CHANGING THE FOLLOWING PROPERTY DECLARATION ORDER !!!!!!! //// //// FOR EXPERTS ONLY: NOT UNTIL EF 5.0 is released! ////

    :)

    Wednesday, August 29, 2012 2:24 PM
  • Hi Alan_chen,

    are there any News or Workarounds to get it work? I am using EF5 (Final) and .Net 4.0? Or did i not get the solution?

    best regards,

    Chris

    Wednesday, August 29, 2012 2:27 PM
  • I’ve also run into this problem after upgrading a fairly large solution from .NET 4.0/EF 4 June CTP 2011 to .NET 4.5/EF5.0 RTM.

    In my case I’ve got a base class for all entities:

        public abstract class Entity

        {

            [Key]

            public int ID { get; set; }

            [NotMapped]

            public AccessRight AccessRight { get; set; }

           

            //... more

    that among other things contains a property AccessRights that is stamped with a “calculated” access right based on current user when the entity is read from the DB –  standard stuff I guess.

    Now this works fine in simple scenarios where another Entity inherits directly Entity. But if I have a construct like:

        public class Vehicle : Entity

        {

            //... more

        }

        public class Car : Vehicle

        {

            //... more

        }

        public class Motorcycle : Vehicle

        {

            //... more

        }

        public class Driver : Entity

        {

            public Vehicle Vehicle { get; set; }

        }

     gives, when using .NET 4.5/EF5.0, the “You cannot use Ignore method on the property…” exception when EF tries to create the database schema but works fine on .NET 4.0/EF.4 June CTP. Now copying the above code into a plain vanilla project actual works so there is something else going on but I have not been able to track it down. Our solution works if I a remove all places where an entity have a relation to an abstract entity similar to the Driver.Vehicle property above.

    After spending too much time trying various work around with fluent configs I found that making the Entity.AccessRights property Internal (and added assembly: InternalsVisibleTo to a number of assemblies) I can make EF correctly generate the DB schema for our solution.

    I’ve quite sure that this is a bug in EF 5.0 so ADO.NET team please look into this – it is not a long term fix for us to use internal and InternalVisibleTo.

    Contact me if you need more info to track it down.

    best regards,

    /Martin

    • Proposed as answer by ChrisTTian Monday, September 3, 2012 1:35 PM
    Wednesday, August 29, 2012 3:09 PM
  • I have a different solution.

    In EF6 source code, System.Data.Entity.ModelConfiguration.Mappers.TypeMapper class, in method LiftDeclaredProperties(Type, EdmEntityType), replace 

    if (property.DeclaringType != type && entityTypeConfiguration.IgnoredProperties.Any(p => p.IsSameAs(property)))

    with 

    if (property.DeclaringType != type && entityTypeConfiguration.IgnoredProperties.Any(p => p.DeclaringType != property.DeclaringType && p.IsSameAs(property)))

    Actually, I think that

    property.DeclaringType != type &&

     should be deleted as well, but did not dare touching it :D

    • Proposed as answer by ChrisTTian Monday, September 3, 2012 1:35 PM
    Saturday, September 1, 2012 5:40 AM
  • I just noticed that this fix for this bug has been applied to the EF6 code, which looks like it may be a fix for this threads bug.

    I don't have the time to look into it again right now so, has anyone else tested if it fixes our bug?


    Friday, October 12, 2012 1:46 AM
  • Ok, my curiosity got the better of me and I gave it a quick test. So far, it looks like it has fixed the bug.
    Friday, October 12, 2012 2:37 AM