Giter VIP home page Giter VIP logo

lazyentitygraph's People

Contributors

alexfoxgill avatar chinwobble avatar dbroudy avatar jzabroski avatar tystol avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

lazyentitygraph's Issues

System.Reflection.TargetException: 'Non-static method requires a target.' when setting navigation property to null

AutoFixture v4.14.0
LazyEntityGraph v2.3.4

Setup as such:

public class Foo
{
    public Guid IdFoo { get; set; }
    public Guid IdBar { get; set; }
    public virtual Bar Bar { get; set; }
}

public class FooConfiguration : IEntityTypeConfiguration<Foo>
{
    public void Configure(EntityTypeBuilder<Foo> builder)
    {
        // Primary Key
        builder.HasKey(t => t.IdFoo);
        builder.Property(t => t.IdFoo).ValueGeneratedOnAdd();

        // Table & Column Mappings
        builder.ToTable("foos", "foo");
        builder.Property(t => t.IdFoo).HasColumnName("id_foo");
        builder.Property(t => t.IdBar).HasColumnName("id_bar");

        // Relationships
        builder.HasOne(t => t.Bar)
            .WithMany(t => t.Foos)
            .HasForeignKey(d => d.IdBar);
    }
}

public class Bar
{
    public Guid IdBar { get; set; }
    public virtual ICollection<Foo> Foos { get; set; }
}

public class BarConfiguration : IEntityTypeConfiguration<Bar>
{
    public void Configure(EntityTypeBuilder<Bar> builder)
    {
        // Primary Key
        builder.HasKey(t => t.IdBar);
        builder.Property(t => t.IdBar).ValueGeneratedOnAdd();

        // Table & Column Mappings
        builder.ToTable("bars", "bar");
        builder.Property(t => t.IdBar).HasColumnName("id_bar");
    }
}

Unit Test:

[Fact]
public void UnitTest()
{
    var fixture = new Fixture();
    var modelMetaData = ModelMetadataGenerator.LoadFromContext<MyDbContext>(x => new MyDbContext(x));
    var lazyEntityGraphCustomization = new LazyEntityGraphCustomization(modelMetaData);
    fixture.Customize(lazyEntityGraphCustomization);
    fixture.Customize(new IgnoreNonEnumerableVirtualMembersCustomisation());
    fixture.RepeatCount = 0;
    var f = fixture.Create<Foo>();
    f.Bar = null;
}

Last line throws: System.Reflection.TargetException: 'Non-static method requires a target.'

Stack Trace

   at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)
   at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
   at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index)
   at System.Reflection.PropertyInfo.GetValue(Object obj)
   at LazyEntityGraph.Core.CollectionProperty.Add[T,TValue](T obj, PropertyInfo pi, TValue value)
   at LazyEntityGraph.Core.Constraints.ManyToOnePropertyConstraint`2.Rebind(THost host, TProperty previousValue, TProperty value)
   at LazyEntityGraph.Core.Property`2.Set(TProperty value)
   at LazyEntityGraph.Core.Property`2.LazyEntityGraph.Core.IProperty<THost>.Set(Object value)
   at LazyEntityGraph.Core.VirtualPropertyInterceptor`1.Intercept(IInvocation invocation)
   at Castle.DynamicProxy.AbstractInvocation.Proceed()
   at Castle.Proxies.FooProxy.set_Bar(Bar value)
   at Company.Project.Services.UnitTests.Commands.PreProcessors.UnitTests.UnitTest() in path/to/file.cs:line 12

Any further info required please ask

Add EntityFrameworkCore support

Add generator for ModelMetadata from EntityFrameworkCore's DbContext

  • Create LazyEntityGraph.EntityFrameworkCore
  • Add Tests LazyEntityGraph.EntityFrameworkCore.Tests

any way to intercept the automatic entity creation process ?

is there a way to intercept the creation graph for object in the tree ?

say we have

public class A {
public virtual IEnumerable\<B\> someClass {get; set;}
}

public class B {
public string title { get; set; }
}

can we intercept the auto property for title upper in the graph ?

i would have with the fixture.with() operator but it doesn't support assignemnt has it's an expression tree.

GetClrType "Sequence contains no matching element" in LazyEntityGraph.EntityFramework.MetadataProperties

EntityFramework version 6
LazyEntityGraph version 2

Thanks for the great work!

When running the following customization per the documentation:

var entityFrameworkCustomization = new LazyEntityGraphCustomization(
        ModelMetadataGenerator.LoadFromEdmxContext<MyContextType>("MyContextName"));

I am getting an error: "Sequence contains no matching element".

This is happening in LazyEntityGraph.EntityFramework.MetadataProperties.GetClrType() when the code is unable to find a metadata property with a name of http://schemas.microsoft.com/ado/2013/11/edm/customannotation:ClrType.

Am I doing something wrong? Or perhaps the loading from edmx is broken? Either way, a clearer error message would be nice. I am guessing someone with more LazyEntityGraph experience than I will say, "oh, the problem is obvious!"

Add support for .Net7.0

I'm using EF Core 7.0 and have the error:

System.MissingMethodException: "Method not found: 'System.Collections.Generic.IList`1<Microsoft.EntityFrameworkCore.Metadata.Conventions.IModelFinalizingConvention> Microsoft.EntityFrameworkCore.Metadata.Conventions.ConventionSet.get_ModelFinalizingConventions()'."

Cannot add entity back to database

Hi,
I would like to add the Autofixture generated entities back to the database, but I cannot do that because the created objects are of castle proxy type. EF does not recognize them.

I can't run these tests only in memory, I need to add the data to an actual database, so mocking is out of the question.
How can I do that ?

Having a base abstract migration breaks loading metadata from code first context

Hi!

I tried to incorporate this library in my tests but I got an exception: System.MissingMethodException: 'Cannot create an abstract class.'.
The problem seems to be in CodeFirstMetadataWorkspaceFactory.GetCacheName(), where the method tries to instantiate the base abstract migration.

Steps to reproduce:

  1. Have an abstract migration in the same project as your DbContext
  2. Try to load metadata
    var metadata = ModelMetadataGenerator.LoadFromCodeFirstContext(str => new AppDbContext(str), true);

can't add created object to DBSet

Since the created POCO objects are of a castle proxy type I can't add them to a DBSet since the type is not known to EF. EF only knows his own proxy type that is emitted at runtime.
Is there a way to work around that problem? Or would the solution be to let the castle proxy inherit from the EF proxy type instead of the POCO type?

Add support for .Net6.0

Although LazyEntityGraph.EntityFrameworkCore is complied against netstandard its compiled against very old versions of EfCore.
When added it against EfCore 6.0.11 we are getting missing method exception for ClrType Property.
See - dotnet/efcore#26701 - This property was removed in EfCore 6.x versions.

Could please compile and publish the packages against newer version of EntityFrameworkCore to add support for .Net6.0

Error:
Method not found: 'System.Type Microsoft.EntityFrameworkCore.Metadata.ITypeBase.get_ClrType()

StackTrace:
at LazyEntityGraph.EntityFrameworkCore.ModelMetadataGenerator.<>c.b__1_0(IEntityType x)
at System.Linq.Enumerable.SelectEnumerableIterator2.MoveNext() at System.Collections.Generic.HashSet1.UnionWith(IEnumerable1 other) at System.Collections.Generic.HashSet1..ctor(IEnumerable1 collection, IEqualityComparer1 comparer)
at System.Linq.Enumerable.DistinctIterator1.ToList() at LazyEntityGraph.Core.ModelMetadata..ctor(IEnumerable1 entityTypes, IEnumerable1 constraints) at LazyEntityGraph.EntityFrameworkCore.ModelMetadataGenerator.GenerateModelMetadata(DbContext ctx) at LazyEntityGraph.EntityFrameworkCore.ModelMetadataGenerator.LoadFromContext[TContext](Func2 createContext)
at App.Test.Configure.ConfigureFixture(Boolean isConfigureMembers) in AutoFixtureData.cs:line 78

[EF Core] 3.x breaking change: "Method not found: [...] IProperty.get_ClrType()"

When attempting to use this repository with EF Core 3.1.4, I am getting the following:

System.MissingMethodException : Method not found: 'System.Type Microsoft.EntityFrameworkCore.Metadata.IProperty.get_ClrType()'.
   at LazyEntityGraph.EntityFrameworkCore.ModelMetadataGenerator.GetForeignKeyConstraint(INavigation navProp)
   at LazyEntityGraph.EntityFrameworkCore.ModelMetadataGenerator.GetConstraints(INavigation from, INavigation to)+MoveNext()
   at System.Linq.Enumerable.SelectManySingleSelectorIterator`2.MoveNext()
   at System.Linq.Set`1.UnionWith(IEnumerable`1 other)
   at System.Linq.Enumerable.DistinctIterator`1.FillSet()
   at System.Linq.Enumerable.DistinctIterator`1.ToList()
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at LazyEntityGraph.Core.ModelMetadata..ctor(IEnumerable`1 entityTypes, IEnumerable`1 constraints)
   at LazyEntityGraph.EntityFrameworkCore.ModelMetadataGenerator.GenerateModelMetadata(DbContext ctx)
   at LazyEntityGraph.EntityFrameworkCore.ModelMetadataGenerator.LoadFromContext[TContext](Func`2 createContext)

Customization code:

LazyEntityGraphCustomization customization = new LazyEntityGraphCustomization(
        ModelMetadataGenerator.LoadFromContext<EfcTestDataContext>(options => new EfcTestDataContext(options)));

It appears this method was removed in EF Core 3.0.

Navigating to property changes parent properties

When accessing the navigation property of an entity that I've used AutoFixture to put into a test method, it changes non-navigation properties of the parent type that are related to the navigation property I accessed.

For example, if I had these two related entities, not related by convention but rather by attributes:

public class First
{
    [Key]
    public int FirstKey { get; set; }

    public int SecondKey { get; set; }

    public virtual Second Second { get; set; }

    public string SomeOtherProperty { get; set; }
}

public class Second
{
    [Key]
    public int SecondKey { get; set; }

    ... other stuff
}

Then passing these through the ModelMetadataGenerator.LoadFromCoadFirstContext(...) and customizing my fixture...

When I put it in a test, like so...

// Using NUnit 3 and NSubstitute
[Test]
[AutoNSubstituteData] //This is my custom class that adds the AutoFixture.NSubstitute customization
public void Test(First first)
{
    var firstKey = first.FirstKey; //Returns an auto-generated number, say 10
    var someOtherProperty = first.SomeOtherProperty; //Returns an auto-generated string, say "abc123"
    var firstKeysSecondKey = first.SecondKey; //Returns, say, 105

    var secondKey = first.Second.SecondKey; //Returns, say, 75
    var afterAccessingNavigation = first.FirstKey; //Now returns 75
    var anotherProperty = first.SomeOtherProperty; //Returns a different auto-generated string, say "123abc"
}

If that didn't make sense, basically when accessing navigation properties that have a relationship back to the accessing member, that member is re-generated completely.

Of course, this keeps the "integrity" of the property constraints, which is probably desired in most cases.

However, I might expect first.SecondKey to remain 105, and the first.Second.SecondKey to also be generated as 105, and SomeOtherProperty to not change from the original value.

Scouring through the metadata that ModelMetadataGenerator created, I found it made these contraints:

OneToManyPropertyConstraint<Second,First>
  PropInfo = ICollection<First>
  _inverse = Second

The workaround is to access navigation properties up-front/immediately, as in make a first.Second.SecondKey call first, and then reference/use/expect/test against/etc the other variables as they will no longer change.

Need a .NET standard 2.1 port of LazyEntityGraph.EntityFramework package, please

Hello, we are using the LazyEntityGraph.EntityFramework package (.NET framework).
In about 5 weeks we are going to migrate our solution to .NET standard 2.1 and EF 6.4.

So, it would be great if you could provide .NET standard 2.1 support for the package.

P.S. You could cover both .NET standard 2.1 and .NET 4.5.2 via multi-target.

Support one sided navigation properties

Hi,
I'm having a problem with my model, which makes use of one sided navigation properties, which doesn't seem to be supported.
For example;

class Foo
{
    public int Id { get; set; }
    public int BarId { get; set; }
    public virtual Bar Bar { get; set; }
}
class Bar
{
    public int Id { get; set; }
}
class Context : DbContext
{
    void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<Foo>()
               .HasOne(f => f.Bar)
               .WithMany()
               .HasForeignKey(f => f.BarId);
    }
}

I have added support for this, if you accept pull requests.

Incompatible with Moq 4.18.1

Restoring packages for C:\Users\daval\source\repos\InfinityBlocks\Test\Test.csproj...
CACHE https://api.nuget.org/v3/vulnerabilities/index.json
CACHE https://api.nuget.org/v3-vulnerabilities/2024.01.12.23.26.44/vulnerability.base.json
CACHE https://api.nuget.org/v3-vulnerabilities/2024.01.12.23.26.44/2024.01.15.17.27.04/vulnerability.update.json
NU1107: Version conflict detected for Castle.Core. Install/reference Castle.Core 5.1.1 directly to project Test to resolve this issue.
Test -> Moq 4.20.70 -> Castle.Core (>= 5.1.1)
Test -> LazyEntityGraph.AutoFixture 2.4.0 -> LazyEntityGraph 2.4.0 -> Castle.Core (>= 4.2.0 && < 5.0.0).
Package restore failed. Rolling back package changes for 'Test'.
Time Elapsed: 00:00:00.1649144
========== Finished ==========

Split testing utilities

Split out testing utilities and make specialized constructors into extension methods to simplify core project dependencies.

Generic constructors to the constraints are only used for testing. Runtime methods only need the PropertyInfo. Splitting these out allows the same degree of testability, with less code in the runtime libraries.

Exception when accessing collection property if it is defined in base class

Hi! I get exception when adding generated entities to EF. Internally in AddAsync() method EF access one of my collection properties.

Brief description of my schema:

namespace A.B.C.Entities
{
    public abstract class BaseEntity
    {
        public int Id { get; set; }
    }

    public abstract class LocalizedEntity<T> : BaseEntity
        where T : Localization
    {
        public virtual ICollection<T> Localizations { get; set; }
    }

    public abstract class Localization : BaseEntity
    {
        public string LanguageCode { get; set; }
    }

    public class SomeEntity : LocalizedEntity<SomeEntityLocalized>
    {
        public string Name { get; set; }
    }

    public class SomeEntityLocalized : Localization
    {
        public string Name { get; set; }

        public virtual SomeEntity LocalizationFor { get; set; }
    }
}

And while adding some of related entities that have references to above ones, I get such exception:

System.InvalidCastException: Unable to cast object of type 'LazyEntityGraph.Core.Property`2[A.B.C.Entities.SomeEntityLocalized,A.B.C.Entities.SomeEntity]' to type 'LazyEntityGraph.Core.IProperty`2[A.B.C.Entities.SomeEntityLocalized,A.B.C.Entities.LocalizedEntity`1[A.B.C.Entities.SomeEntityLocalized]]'.
    at LazyEntityGraph.Core.VirtualPropertyInterceptor`1.Get[TProp](PropertyInfo propInfo)

InvalidOperationException if a context has foreign keys upon multiple columns

Hi!

I tried to connect this library to the project I work on but found the issue which makes it impossible for us to use it because it throws InvalidOperationException on initialization. The investigation shows that the reason is that some of the foreign keys we have been set upon multiple columns, while LazyEntityGraph expect there is alwas a single one:

IPropertyBase fkPrincipalProp = fkProp.PrincipalKey.Properties.Single();
var foreignKeyPropInfo = fkProp.Properties.Single().PropertyInfo;

Here I came up with the test reproducing the issue and I was hoping I'll be able to fix it myself and submit a pull request but it seems, this can be more tricky that I can handle.

@dbroudy do you maybe have an idea about how this can be fixed?

Does not work with EF.Core 3. if you don't explicitly add a reference to Microsoft.EntityFrameworkCore.InMemory 3

Using Entity Framework Core 3.1.5, if I add LazyEntityGraph.EntityFrameworkCore to my project, it pulls Microsoft.EntityFrameworkCore.InMemory 2.0.0, which is not compatible with 3.1.* (Probablaly 3.0 too).
It crashes on the following code, of LazyEntityGraph.EntityFrameworkCore\ModelMetadataGenerator.cs with an exception that says "Method 'get_Info' in type InMemoryOptionsExtension not implemented"

 var options = new DbContextOptionsBuilder<TContext>()
                .UseInMemoryDatabase(databaseName: "App=EntityFrameworkCore")
                .Options;

Work-around is to explicitly add a reference to Microsoft.EntityFrameworkCore.InMemory (installing the nuget package) to the matching version (3.1.5, in my case).

While I'm not sure how this can be fixed in the code/builds/packages themselves, I think it should at least be documented on the Wiki, the Front-page or the Getting Stated.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.