I try to map a list of objects with ValueInjecter using a LINQ query like this :
var thingsCollection = rep.Things.Select(x => new ThingDTO().InjectFrom(x) as ThingDTO)
.OrderByDescending(x => x.StartDate).ToList();
The problem is that the Thing and the ThingDTO objects contain other objets :
public class ThingDTO
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public MaterialDTO Material{ get; set; }
}
What kind of injection method should I use to get the sub object map ? Or do I have to do a foreach instead of the LINQ query ?
you would have to do it manually for each new mapped object you need to instantiate the collection manually and add the new mapped elements
Related
Problem: I'm calling a stored procedure through EF Core. When I run the stored procedure directly (via 'debug procedure'), it runs quickly, but it runs VERY slowly when called by EF's FromSqlRaw. So the problem appears to be when converting the returned data-table to a list of objects.
Setup:
Simple application with a list of blog posts. The stored procedure gets a hierarchical list of posts and associated users from a TPH table of posts, plus a table of users.
// Code is simplified, actually 8 parameters
SqlParameter depth_p = new SqlParameter("#depth", depth);
SqlParameter authorizedUserID_p = new SqlParameter("#authorizedUserID", authorizedUser.ID);
IQueryable<PostUser> query = postContext.PostUsers
.FromSqlRaw("Post.USP_ReadDebate #depth, #authorizedUserID",
parameters: new[] { depth_p, authorizedUserID_p });
List<PostUser> postUsers = query.ToList(); // This hangs.
26 columns are returned and converted by EF into the PostUser class.
PostUser holds 26 "ordinary" properties. No navigation properties, custom classes or any getters or setters that do any work.
public class PostUser
{
// Post fields
public Int32? ID { get; set; } // Primary Key
public String Text { get; set; }
public Guid OwnerID { get; set; }
public int? ParentID { get; set; } // nullable
public bool IsDisabled { get; set; }
public DateTime TimeCreated { get; set; }
public bool User_IsBanned { get; set; } = false;
// some others...
public PostUser() { }
}
Note: the stored procedure is very complex. It calls another stored procedure which fills a #spid table, then inserts the contents of that #SPID table into a table variable and returns that.
But again when debugged directly it returns quickly, so I think the problem is when EF Core is converting the returned data to the PostUser object.
Bottom Line: is there any way to get visibility into what EF Core is doing on the conversion to PostUser to find the problem?
Thank you!
I have built a new Web Application that uses the template Visual Studio provides and included MVC and Web API. The default authorization mechanism is Identity and the database interaction is done using Entity Framework with Code-first method of creating the database.
I have three requirements:
A user can have a list of Children objects
I do not want to use a "relationship" object
All users already exist on the AspNetUsers table, because they all need to be able to login, so I do not want another table to maintain user data
In theory, multiple parents could have reference to multiple children, but for this example, we will just consider it a one-to-many relationship.
In my application, I need to have an ApplicationUser have a list of ChildUsers as a collection of ApplicationUser such as shown below.
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
public string ShirtSize { get; set; }
public ICollection<ApplicationUser> Children { get; set; }
}
I want these users to be accessible as shown above (a collection of ApplicationUser), not a collection of Relationship object that ties them together such as:
public class Relationship
{
public String ParentId { get;set; }
public String ChildId { get;set; }
}
Can a new table be created and exist on the database without having a code-first model for it to know how to create a relationship table?
What are available solutions to this problem?
After some research, and experimentation, I have found bits and pieces of guidance to arrive at a solution that works.
In order for an intermediate table to be created to maintain the relationship, the ApplicationDbContext OnModelCreating function needs to know what it should look like. I have told it to create a new table that is not bound to an object by using the modelBuilder shown in the code below. Unfortunately, I do not have the links to the articles that guided me to this.
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base( "DefaultConnection", throwIfV1Schema: false )
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
protected override void OnModelCreating( DbModelBuilder modelBuilder )
{
base.OnModelCreating( modelBuilder );
modelBuilder.Entity<ApplicationUser>()
.HasMany( p => p.ChildUsers )
.WithMany()
.Map( m =>
{
m.MapLeftKey( "Father_Id" );
m.MapRightKey( "Son_Id" );
m.ToTable( "father_son_relation" );
} );
}
}
Additionally, when you need to add Children to the parent ApplicationUser, you will need to do some tweaking as you are about to insert so that it updates the database correctly. I definitely want the UserManager to do the creation of the user for me, but that means that when I go to add the user to my list of Children with the code below, it tries to add it again and throws an exception because it already exists.
var result = await UserManager.CreateAsync( user, model.Password );
var myUserId = User.Identity.GetUserId();
var users = AppDbContext.Users.Where( u => u.Id == myUserId ).Include( u => u.ChildUsers );
var u2 = users.First();
u2.ChildUsers.Add( user );
await AppDbContext.SaveChangesAsync();
After finding this question, I researched the EntityStates and found that adding the following line before calling SaveChanges resolved the exception and it no longer attempts to add it again.
AppDbContext.Entry( user ).State = EntityState.Unchanged;
TADA!!! Now to select them from the database using EF, you can then use the following code:
AppDbContext.Users.Where( u => u.Id == myUserId ).Include( u => u.Children ).First();
Since I am only getting one level of Children this will work ok, after that you risk circular references.
Comments and ideas to improve the code are welcome.
Here is the problem I need to solve:
I need to display a grid that contains a group of columns that are dynamic, meaning that the number can change depending on the user parameters.
I have attached a sample below as an image to illustrate:
GRID SAME IMAGE
I have these c# POCOs to keep my question simple
public class OrderItem
{
public string ProductName { get; set; }
public string Status { get; set; }
public List<CityOrderInfo> CityOrders { get; set; }
}
public class CityOrderInfo
{
public int OrderCount { get; set; }
}
I have a web api controller that is able to accept the OData request, plus other arguments that the repository accepts. However the problem is that while the parameter $orderby for ProductName and Status works, when I do "$orderby='CityOrders[1]\OrderCount asc' it fails.
public class OrdersControllers : ApiController
{
private readonly IOrdersRepository _repository;
public OrdersControllers(IOrdersRepository repository)
{
this._repository = repository;
}
public IEnumerable<OrderItem> GetOrderItems([FromUri] ODataQueryOptions<OrderItem> oDataQuery)
{
var result = this._repository.GetOrders().ToList();
var queryableData = oDataQuery.ApplyTo(result.AsQueryable());
var transformedData = queryableData as IEnumerable<OrderItem>;
return transformedData;
}
}
The reason I opted to hold the city orders in list is because I thought it would too painful to make a POCO with every city in the USA as a property so instead made it more generic.
The question is how can a sort on a property that holds a list using OData? Is this possible? I keep getting syntax error at position n. As of now I have not found an answer.
Considering the document { "userName": "user1" } stored in the User collection, and the following User class:
public class User
{
public string Id { get; set; }
public string UserName { get; set; }
}
With the following JSON.net settings:
JsonConvert.DefaultSettings = () =>
{
return new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
};
};
When I query with Linq as such:
var t = _client.CreateDocumentQuery<User>(_collection.SelfLink)
.Where(u => u.UserName == "user1").AsDocumentQuery().ExecuteNextAsync();
t.Wait();
var users = t.Result;
var user = users.FirstOrDefault();
user is null. Changing the Document to have a pascal casing or the POCO to use a camel casing solves the issue. Of course I do not want any of those as I want my JSON objects and C# objects to be "standarized".
How can I tell the DocumentDB SDK to map my object's property names using camel casing, similar as JSON.net?
The DocumentDB LINQ provider does not pick up the JsonConvert.DefaultSettings. In general you can use the DefaultSettings to control camelCase, but for those properties you wish to use in a LINQ Where clause must have the name explicitly set using JsonProperty attribute on your DTO.
public class User
{
public string Id { get; set; }
[JsonProperty("userName")]
public string UserName { get; set; }
}
Although a bit tedious and a good source for bugs, it seems to be your only option for now.
In a similar case with Cosmos DB, I was able to set all properties to Camel case for my objects at the class declaration level, as in:
[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class User
{
public string Id { get; set; }
public string UserName { get; set; }
}
This is how you tell NewtonSoft.Json to use Camel case for serializing.
In newer SDK's you can control the linq serialization in the following way:
container.GetItemLinqQueryable<T>(
linqSerializerOptions: new CosmosLinqSerializerOptions
{
PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase
});
Where container is an Microsoft.Azure.Cosmos.Container.
Here is my Session Class
public static class Sessions
{
public class UserSession
{
public string CurrentSelected
{
get;
set;
}
public string Req
{
get;
set;
}
public DateTime Reque
{
get;
set;
}
public List<Options> Option;
}
public class Option
{
public string Te;
public string Fe;
public string Fg;
public string DE;
}
}
I create a new session of my class
Session["SessionStats"] = new UserSession();
Then I try to add to the List
foreach(string hello in helloworld) {
Options RO = new Options();
RO.DE = item.GetDataKeyValue("DE").ToString();
RO.Fg = item.GetDataKeyValue("Fg").ToString();
RO.Fe = item.GetDataKeyValue("Fe").ToString();
RO.Te = item.GetDataKeyValue("Te").ToString();
}
This is where the error occurs
((UserSession)Session["SessionStats"]).Options.Add(RO);
RO is correctly populated but ((UserSession)Session["SessionStats"]).Option is null, I'm not sure how to add RO to this list. This has to be a list because I have like 10 RO's I need to put in this list.
After
Session["SessionStats"] = new UserSession();
you have added a new UserSession, whose Option property is null, to Session. Then, when you do
((UserSession)Session["SessionStats"]).Options.Add(RO);
you are pulling out that very same object and accessing the Option property, which is null, hence the NullReferenceException.
It looks like you are forgetting to assign something to the newly created UserOption's Option property. However, you don't seem to be using the Options you are instantiating in the foreach for anything...
You are mixing 'Option' and 'Options'. Change the class name from 'Option' to 'Options'. Then change this line:
((UserSession)Session["SessionStats"]).Options.Add(RO);
to
((UserSession)Session["SessionStats"]).Option.Add(RO);