I have an Code First model: I am attempting to use Include() and IncludeThen() and get a System.ArgumentNullException .
Here are the entities (let me know if you'd like more of the model):
public class Area
{
public Area()
{
Geocode = new List<Geocode>();
}
public int AreaId { get; set; }
public int InfoId { get; set; }
public string AreaDescription { get; set; }
public string Polygon { get; set; }
public string Circle { get; set; }
public List<Geocode> Geocode { get; set; }
public string Altitude { get; set; }
public string Ceiling { get; set; }
}
public class Geocode
{
public Geocode(string valueName, string value
)
{
ValueName = valueName;
Value = value;
}
public int GeocodeId { get; set; }
public int AreaId { get; set; }
public string ValueName { get; set; }
public string Value { get; set; }
}
Here is the calling code:
context.Alerts.Include(f => f.Infos)
.ThenInclude(f => f.Areas)
.ThenInclude(f => f.Geocode);// When I comment out this line it does not error, just doesn't load the Geocode navigation property.
Here is a stack trace:
at System.Linq.Expressions.Expression.New(ConstructorInfo constructor, IEnumerable1 arguments)
at Microsoft.Data.Entity.Metadata.Internal.EntityMaterializerSource.CreateMaterializeExpression(IEntityType entityType, Expression valueBufferExpression, Int32[] indexMap)
at Microsoft.Data.Entity.Query.ExpressionVisitors.Internal.MaterializerFactory.CreateMaterializer(IEntityType entityType, SelectExpression selectExpression, Func3 projectionAdder, IQuerySource querySource)
at Microsoft.Data.Entity.Query.ExpressionVisitors.Internal.IncludeExpressionVisitor.d__13.MoveNext()
at System.Collections.Generic.List1..ctor(IEnumerable1 collection)
at System.Dynamic.Utils.CollectionExtensions.ToReadOnly[T](IEnumerable1 enumerable)
at System.Linq.Expressions.Expression.NewArrayInit(Type type, IEnumerable1 initializers)
at Microsoft.Data.Entity.Query.ExpressionVisitors.Internal.IncludeExpressionVisitor.VisitMethodCall(MethodCallExpression expression)
at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
at Microsoft.Data.Entity.Query.ExpressionVisitors.ExpressionVisitorBase.Visit(Expression expression)
at Microsoft.Data.Entity.Query.RelationalQueryModelVisitor.IncludeNavigations(IncludeSpecification includeSpecification, Type resultType, LambdaExpression accessorLambda, Boolean querySourceRequiresTracking)
at Microsoft.Data.Entity.Query.EntityQueryModelVisitor.IncludeNavigations(QueryModel queryModel, IReadOnlyCollection1 includeSpecifications)
at Microsoft.Data.Entity.Query.RelationalQueryModelVisitor.IncludeNavigations(QueryModel queryModel, IReadOnlyCollection1 includeSpecifications)
at Microsoft.Data.Entity.Query.EntityQueryModelVisitor.IncludeNavigations(QueryModel queryModel)
at Microsoft.Data.Entity.Query.EntityQueryModelVisitor.CreateQueryExecutor[TResult](QueryModel queryModel)
at Microsoft.Data.Entity.Storage.Database.CompileQuery[TResult](QueryModel queryModel)
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.Data.Entity.Query.Internal.QueryCompiler.<>c__DisplayClass18_01.<CompileQuery>b__0()
at Microsoft.Data.Entity.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func1 compiler)
at Microsoft.Data.Entity.Query.Internal.QueryCompiler.CompileQuery[TResult](Expression query)
at Microsoft.Data.Entity.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
at Microsoft.Data.Entity.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
at Remotion.Linq.QueryableBase1.GetEnumerator()
at Microsoft.Data.Entity.EntityFrameworkQueryableExtensions.IncludableQueryable2.GetEnumerator()
at WeatherMonitoringConsole.Program.<>c__DisplayClass0_0.<b__0>d.MoveNext() in C:\Users\ehasson\Source\Workspaces\Marketing\WeatherMonitoring\WeatherMonitoringConsole\Program.cs:line 32
The problem was I needed a default constructor on each entity.
Related
Source code for this problem is on GitHub
I have the following dbContext for a legacy data structure.
[TypesInfoInitializer(typeof(OrgsContextInitializer))]
public class OrgsEFCoreDbContext : DbContext
{
public OrgsEFCoreDbContext(DbContextOptions<OrgsEFCoreDbContext> options) : base(options)
{
}
public DbSet<ModuleInfo> ModulesInfo { get; set; }
public DbSet<ModelDifference> ModelDifferences { get; set; }
public DbSet<ModelDifferenceAspect> ModelDifferenceAspects { get; set; }
public DbSet<PermissionPolicyRole> Roles { get; set; }
public DbSet<ApplicationUser> Users { get; set; }
public DbSet<ApplicationUserLoginInfo> UserLoginInfos { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<Supplier> Suppliers { get; set; }
public DbSet<CustomerContact> CustomerContacts { get; set; }
public DbSet<SupplierContact> SupplierContacts { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ApplicationUserLoginInfo>(b =>
{
b.HasIndex(nameof(DevExpress.ExpressApp.Security.ISecurityUserLoginInfo.LoginProviderName), nameof(DevExpress.ExpressApp.Security.ISecurityUserLoginInfo.ProviderUserKey)).IsUnique();
});
modelBuilder.Entity<Organization>().ToTable("Organizations");
modelBuilder.Entity<Organization>().HasDiscriminator(x => x.OrganizationType)
.HasValue<Customer>(1)
.HasValue<Supplier>(2)
;
modelBuilder.Entity<Contact>().ToTable("Contacts");
modelBuilder.Entity<Contact>().HasDiscriminator(x => x.ContactType)
.HasValue<CustomerContact>(1)
.HasValue<SupplierContact>(2)
;
}
}
When I add a CustomerContact to a Customer I get an error
Unable to cast object of type 'Orgs.Module.BusinessObjects.CustomerContact' to type 'Orgs.Module.BusinessObjects.SupplierContact'.
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.get_Item(IPropertyBase propertyBase)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.GetCurrentValue(IPropertyBase propertyBase)
at DevExpress.EntityFrameworkCore.Security.NetStandard.ChangeTracking.SecurityStateManager.TryAddPropertyNameToCollection(InternalEntityEntry entity, ICollection`1 propertiesToCheck, IPropertyBase property)
at DevExpress.EntityFrameworkCore.Security.NetStandard.ChangeTracking.SecurityStateManager.TryAddPropertyNameToCollection(InternalEntityEntry entity, IProperty property, ICollection`1 propertiesToCheck)
at DevExpress.EntityFrameworkCore.Security.NetStandard.ChangeTracking.SecurityStateManager.GetPropertiesToCheck(InternalEntityEntry entity)
at DevExpress.EntityFrameworkCore.Security.NetStandard.ChangeTracking.SecurityStateManager.CheckReadWritePermissionsForNonIntermediateObject(InternalEntityEntry entity)
at DevExpress.EntityFrameworkCore.Security.NetStandard.ChangeTracking.SecurityStateManager.CheckReadWritePermissions(InternalEntityEntry entity)
at DevExpress.EntityFrameworkCore.Security.NetStandard.ChangeTracking.SecurityStateManager.CheckIsGrantedToSave(InternalEntityEntry entity)
at DevExpress.EntityFrameworkCore.Security.NetStandard.ChangeTracking.SecurityStateManager.GetEntriesToSave(Boolean cascadeChanges)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(DbContext _, Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges()
at DevExpress.ExpressApp.EFCore.EFCoreObjectSpace.DoCommit()
at DevExpress.EntityFrameworkCore.Security.SecuredEFCoreObjectSpace.DoCommit()
at DevExpress.ExpressApp.BaseObjectSpace.CommitChanges()
at DevExpress.ExpressApp.Win.SystemModule.WinModificationsController.Save(SimpleActionExecuteEventArgs args)
at DevExpress.ExpressApp.SystemModule.ModificationsController.saveAction_OnExecute(Object sender, SimpleActionExecuteEventArgs e)
at DevExpress.ExpressApp.Actions.SimpleAction.RaiseExecute(ActionBaseEventArgs eventArgs)
at DevExpress.ExpressApp.Actions.ActionBase.ExecuteCore(Delegate handler, ActionBaseEventArgs eventArgs)
The error is the other way around if I try to add a supplier contact to a supplier.
The business classes are as follows;
[NavigationItem("Data")]
public class Customer : Organization
{
public Customer()
{
Contacts = new List<CustomerContact>();
}
public virtual List<CustomerContact> Contacts { get; set; }
}
public class CustomerContact : Contact
{
public CustomerContact() {}
[ForeignKey("OrganizationId")]
public virtual Customer Customer { get; set; }
}
public abstract class Organization
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public string Comments { get; set; }
public int OrganizationType { get; set; }
}
public abstract class Contact
{
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int ContactType { get; set; }
public int OrganizationId { get; set; }
}
At run time the user experience is
Looking at the instructions here I am unsure if this is a Dev Express issue or an Entity Framework issue.
Model:
public partial class FN_Result
{
public string UserImage { get; set; }
public string UserName { get; set; }
public string Title { get; set; }
public int messageId { get; set; }
public int SenderId { get; set; }
public int ReceiverId { get; set; }
public string MessageText { get; set; }
public bool MessageStatus { get; set; }
public bool IsAdmin { get; set; }
public bool IsClinician { get; set; }
public string CreatedOn { get; set; }
public int RowNum { get; set; }
}
Constructor and variable declaration:
private readonly IDbConnection db;
public DbContext(DbContextOptions<DbContext> options, IConfiguration configuration)
: base(options)
{
this.Configuration = configuration;
this.db = new SqlConnection(this.Configuration.GetConnectionString("PortalDb"));
}
We have the following DbFunction in an MVC project .NET 5.0
[DbFunction("namespace", "FN_Name")]
public async Task<IEnumerable<FN_Result>> FN_MethodName(int id)
{
var parameters = new DynamicParameters();
parameters.Add("#id", id);
return await this.db.QueryAsync<FN_Result>("[namespace].[FN_Name](#id)", parameters, commandType: CommandType.Text);
}
IEnumerable<FN_Result> is indeed the return type of db.QueryAsync<FN_Result>
However it's throwing the following error message: Message=The DbFunction 'dbPortalContext.FN_Name([System.Int32, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e])' has an invalid return type 'Task<IEnumerable<FN_Result>>'. Ensure that the return type can be mapped by the current provider.
We have also tried converting it into a List, to no avail
I'm trying to save a object Using HTTP Post Method in my API Controller, but it's returning a error, i've tried to do the same in another controler and it works. I hope you may help!
The Request that I tried:
{
"integrationServiceHost": "10.80.80.10",
"RouterHost": "10.80.80.10",
"Enabled": "false",
"IntegrationServiceRemotePort": "1234",
"RouterSocketPort":"1234",
"RouterRemotePort":"1234",
"IDChannelBehavior":"10",
"IDEPS":"1",
"Description":"Teste Whats",
"IDChannel":"0"
}
ChannelWhatsapp Class:
public class ChannelWhatsApp : Channel
{
public ChannelWhatsApp();
[Column("WHATSAPP_UserName")]
public string UserName { get; set; }
[Column("WHATSAPP_Password")]
public string Password { get; set; }
[Column("WHATSAPP_DisplayName")]
public string DisplayName { get; set; }
}
url : http://172.19.22.81:5000/api/channelWhatsapp/saveDto
Channel Class :
public abstract class Channel : NotifyPropertyChanged
{
public Channel();
public virtual ICollection<Interaction> Interaction { get; set; }
public virtual ICollection<Schedule> Schedule { get; set; }
public virtual ICollection<Queue> Queue { get; set; }
public virtual ICollection<Session> Session { get; set; }
public virtual ChannelBehavior ChannelBehavior { get; set; }
public virtual EPS EPS { get; set; }
public DateTime? DtLastChange { get; set; }
[MaxLength(100)]
public string IntegrationServiceHost { get; set; }
[MaxLength(100)]
public string RouterHost { get; set; }
public bool Enabled { get; set; }
public int? IntegrationServiceRemotePort { get; set; }
public int? RouterSocketPort { get; set; }
public int? RouterRemotePort { get; set; }
[ForeignKey("ChannelBehavior")]
public int IDChannelBehavior { get; set; }
[ForeignKey("EPS")]
public int IDEPS { get; set; }
[MaxLength(200)]
public string Description { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int IDChannel { get; set; }
[NotMapped]
public string IconName { get; set; }
[NotMapped]
public byte? PendingPauseCode { get; set; }
[NotMapped]
public bool IsPausePending { get; set; }
[NotMapped]
public SystemUserOperator Operator { get; set; }
[NotMapped]
public DateTime StateMomment { get; set; }
[NotMapped]
public UserStateType CurrentState { get; set; }
public virtual ICollection<ChannelSkill> ChannelSkills { get; set; }
[NotMapped]
public ChannelTypeType Type { get; set; }
}
My Controller:
[Route("api/ChannelWhatsapp/{Action}")]
[ApiController]
public class ChannelWhatsappController : IrideController<ChannelWhatsApp>
{
public ChannelWhatsappController(IrideContext context) : base(context) { }
[HttpPost("")]
[ActionName("saveDto")]
public IActionResult saveDto([FromBody] ChannelWhatsApp entity)
{
try
{
////Obtem o data
//entity.DtLastChange = IrideUtil.getDate() ;
//_context.Set<ChannelWhatsApp>().Update(entity);
//_context.SaveChanges();
return Ok(entity);
}
catch (Exception ex)
{
return Ok(ex.ToString());
}
}
}
returned error:
Exception: Invalid channel IrideCM.Model.Channel..ctor()
IrideCM.Model.ChannelWhatsApp..ctor() lambda_method(Closure )
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateNewObject(JsonReader
reader, JsonObjectContract objectContract, JsonProperty
containerMember, JsonProperty containerProperty, string id, out bool
createdFromNonDefaultCreator) in JsonSerializerInternalReader.cs
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader
reader, Type objectType, JsonContract contract, JsonProperty member,
JsonContainerContract containerContract, JsonProperty containerMember,
object existingValue) in JsonSerializerInternalReader.cs
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader
reader, Type objectType, bool checkAdditionalContent) in
JsonSerializerInternalReader.cs
When posting a payload to a controller in the request's body, you need to make sure the payload's structure matchs the structure of the expected class.
In your case, it does not match at all. You just need to post a payload with the same type as the type expected in the FromBody param of your endpoint.
I'm using a GenericRepository to work with Eager Loading on EF Core, in this case i can loading CategoriaNutrientes but if i try to load Nutriente
categoriaService.FindBy((i => i.CategoriaNutrientes.Select(x=>x.Nutriente)))
i've got this error:
System.InvalidOperationException: 'The property expression 'i => {from
ManyToManyChild x in [i].ManyToManyChilds select [x].GrandChild}'
is not valid. The expression should represent a property access: 't =>
t.MyProperty'. For more information on including related data, see
http://go.microsoft.com/fwlink/?LinkID=746393.'
public class Categoria:BaseEntidadeExecutora
{
public Int64 Id { get; set; }
public string NomeCategoria { get; set; }
public Int64 QtdeMinimaRefeicao { get; set; }
public string FormaCalculo { get; set; }
public Int64 NecessidadeDiariaMinima { get; set; }
public ICollection<CategoriaNutriente> CategoriaNutrientes { get; set; }
public ICollection<UnidadeEnsinoCategoria> UnidadeEnsinoCategorias { get; set; }
}
public class CategoriaNutriente : BaseEntity
{
public Int64 IdCategoria { get; set; }
public Categoria Categoria {get;set;}
public Int64 IdNutriente { get; set; }
public Nutriente Nutriente { get; set; }
public Int64 NecessidadeNutricional { get; set; }
}
categoriaService.FindBy((i => i.CategoriaNutrientes.Select(x=>x.Nutriente)))
public IEnumerable<T> FindBy(params Expression<Func<T, object>>[] includes)
{
IQueryable<T> set = entities;
var entity = (includes.Aggregate(set, (current, include) => current.Include(include)).ToList() ?? default(ICollection<T>));
}
I have a nested list<object>:
public class ItemsOfQuestions {
public string item_title { get; set; }
public Byte item_type { get; set; }
public string item_image { get; set; }
public Int16 item_grade { get; set;}
}
public class Questins_With_Items {
public string question_title { get; set; }
public List<ItemsOfQuestions> list_items { get; set; }
}
I get data from db and set to list,
but I get this error:
The best overloaded method match for
'System.Collections.Generic.List.Add(graph1.ViewModels.ItemsOfQuestions)'
has some invalid arguments
Can anybody help?