ASP.net Core eager loading, let included object be null - asp.net

I am getting all customers and including their linked operator.
The only catch is a customer can exist without an operator.
The problem I am having is when i try include the operator any customer that doesn't have a linked operator is not retrieved is there a way to still retrieve all my customers and if thy do not have an operator just have the operator object within the customer be null?
-get all customers method
public List<Customer> GetAllWithRelations()
{
return Context.Set<Customer>()
.Include(cp => cp.Operator).ToList();
}
-Cusomer object
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public int? OperatorId { get; set; }
[ForeignKey("OperatorId")]
public virtual Operator Operator { get; set; }
}
-Operator Object
public class Operator
{
public int Id { get; set; }
public string Name { get; set; }
}

Although you did not specify a tag for this, by using the .Include I'm guessing it's a EntityFramework Core linq which is breaking.
I've came across the same case on EF whenever the relationship is not set to allow nulls. So, for instance, your mapping might be explicitly setting it to be required or somehow you're not setting it and EF defaults are stablishing a required map between Customer and Operator.
Just set it to optional wherever you're building your model mappings and you'll get the desired behavior.
See: https://learn.microsoft.com/en-us/ef/core/modeling/required-optional

Related

SQLite.net database with Xamarin.Forms App

I have a problem with an SQLite database in my Xamarin.Forms PCL project.
I have followed this example from Microsoft Docs:
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/databases
I've been using my own types to store data and it's worked Ok for simple custom types, but I've recently added List<int> and Attendance type to the custom object (Info).
Now when I try and create the object, i get the following errors:
Don't know about System.Collections.Generic.List`1[System.Int32]
Don't know about MyApp.Attendance
Here is the init code:
readonly SQLiteAsyncConnection database;
database = new SQLiteAsyncConnection(dbPath);
database.CreateTableAsync<UserPrefrences>().Wait();
database.CreateTableAsync<Attendance>().Wait();
database.CreateTableAsync<Info>().Wait();
I'm using Xamarin.Forms with Xamarin.iOS.
You can not store them by default like that. However there is sqlite-net-extensions which you can use to accomplish that. You can take a look about sqlite-net-extensions here.
Using this extension you will be able to do that with TextBlob property, something like this:
public class Address
{
public string StreetName { get; set; }
public string Number { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
}
public class Person
{
public string Name { get; set; }
[TextBlob("PhonesBlobbed")]
public List<string> PhoneNumbers { get; set; }
[TextBlob("AddressesBlobbed")]
public List<Address> Addresses { get; set; }
public string PhonesBlobbed { get; set; } // serialized phone numbers
public string AddressesBlobbed { get; set; } // serialized addresses
}
More explanation about TextBlob from url.
Text blobbed properties Text-blobbed properties are serialized into a text property when saved and deserialized when loaded. This allows
storing simple objects in the same table in a single column.
Text-blobbed properties have a small overhead of serializing and
deserializing the objects and some limitations, but are the best way
to store simple objects like List or Dictionary of basic types or
simple relationships.
Text-blobbed properties require a declared string property where the
serialized object is stored.
I just saw that there is also similar/same questions about this topic on StackOverflow already, so you can take a look at them also.
How can you store lists of objects in SQLite.net?
Can I use a List of String in a class intended for SQLite?

Entity Framework 5 - code first array navigation property one to many with Interface Type

These are my classes:
public class Post : IPost
{
public int Id { get; set; }
public virtual int[] DuplicateOf { get; set; }
public virtual ICommentInfo[] Comments { get; set; }
}
public class CommentInfo : ICommentInfo
{
public virtual string Author { get; set; }
public virtual int Id { get; set; }
public virtual string Text { get; set; }
public virtual int PostId{ get; set; }
[ForeignKey("PostId")]
public virtual Post Post { get; set; }
}
With this CommentConfiguration added to OnModelCreate():
HasRequired(c => c.Post)
.WithMany(b=>(ICollection<CommentInfo>) b.Comments)
.HasForeignKey(b=>b.PostId)
.WillCascadeOnDelete(true);
I really cannot understand why the property Comments is always null, and why EF doesn't initialize it since it's virtual.
I tried disabling lazy loading too, but when i try loading the navigation property with context.Post.Include("Comments") an error tells me that "There is not a navigation property called Comments".
So I tried using Entity Framework Power Tools Beta 3 to see the Entity Data Model, and I discovered that there is not a navigation end for table "Post" even if there is the relationship between the two tables and there's the Comment table end too.
I sincerly don't know which way to turn, could be a problem of Array?? Should I use an Icollection property??
Though I cannot change the type of that property because Post is implementing an Interface.
Every sample I look at is clear and easy to make work. Please help me.. Thank you in advance.
EDIT:
This is what I changed after looking at the link I posted yesterday.
public class Post : IPost
{
public int Id { get; set; }
public virtual int[] DuplicateOf { get; set; }
public virtual ICollection<CommentInfo> Comments { get; set; }
ICommentInfo[] IPost.Comments {
get { return Comments ; }
set { Comments = (CommentInfo[])value; } }
}
The exception is: System.ObjectDisposedException :The ObjectContext instance has been disposed and can no longer be used for operations that require a connection and raises when the application tries to get the Comments.
If I remove the virtual key the exception disappear but the property remain always null and the values don't persist in any way.
EDITv2
I've solved my problem adding a new property and map my old property to it.
public class Post : IPost
{
public int Id { get; set; }
public virtual int[] DuplicateOf { get; set; }
public ICommentInfo[] Comments
{
get { return ListComments.ToArray(); }
}
public List<CommentInfo> ListComments {get;set;}
}
In my PostConfiguration OnModelCreate() I used the ListComments property as a navigation property like this:
HasMany(b => b.ListComments)
.WithRequired(c=>c.Post)
.HasForeignKey(c=>c.PostId)
.WillCascadeOnDelete(true);
Now it perfectly works, it was simpler than I expected and when I try to receive the Comments Collection, if I include the "ListComments" property, I get the array of Post.
Thank you for your help!
I can't access the link in your comment, but I assume you changed
public virtual ICommentInfo[] Comments { get; set; }
into the common way to define navigation properties:
public virtual ICollection<CommentInfo> Comments { get; set; }
because entity framework does not support interfaces in its conceptual model.
The exception about the disposed context means that you access this property after fetching Post objects from the database and disposing the context. This triggers lazy loading while the connection to the database is lost. The solution is to use Include:
var posts = context.Posts.Include(p => p.Comments).Where(...)
Now posts and comments are fetched in one go.

The member with identity does not exist in the metadata collection. Parameter name: identity

We are using EF Code First 4.3.1.
We are developing an ASP.NET Web Role referring to multiple class libraries.
There are two class libraries each containing classes and an individual DBcontext.
Lets say the Library1 has classes A and B.
DBcon1: DbSet and DbSet
Lets say the Library2 has classes C and D.
Class C{
[Key]
public int CId{ get; set;}
[Required]
public virtual A referencedA {get; set;}
}
DBcon2: DbSet<C> and DbSet<D>
When I try to use the DBcon2 as such:
using (var con = new DBcon2())
{
C vr = new C();
vr.CId= 1;
vr.referencedA = DBCon1.As.First();
con.Cs.Add(vr);
con.SaveChanges();
}
I get an exception as:
"The member with identity does not exist in the metadata collection.
Parameter name: identity"
Both DBCon1 and DBcon2 are using the sane SQL Server Database "SampleDB".
Please point me in the right direction.
I got this error and fixed it by not trying to set the navigation property in the related table, just set the foreign key id instead
eg
public class Student()
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public int CourseId { get; set; }
public virtual Course Course { get; set; }
}
public class Course()
{
public int CourseId { get; set; }
public string CourseName { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
Main code:
var myCourse = new Course();
var myCourseId = 1;
var student = new Student() {
CourseId = myCourseId
// Course = myCourse <-- this would cause the error
}
Might not be your issue but maybe it will point you in the right direction and hopefully will help someone else.
The exception is a bit cryptic, but pretty clear if you realise that a context needs information about entities (metadata) to be able to write sql statements. Thus, your DBcon2 context has no clue where to find the primary key of an A, because it has no metadata about A.
You could however set an integer property A_Id (or the like), but then you'll have to write custom code to resolve it to an A.
Another option is to merge (parts of) the contexts, if possible.

Many to one configuration using EF 4.1 code first

I have the following classes:
public class CartItem
{
public long Id { get; set; }
public int Quantity { get; set; }
public Product Product { get; set; }
}
public class Product {
public long Id { get; set; }
public string Title { get; set; }
public decimal Price { get; set; }
}
I currently have the following configuration:
modelBuilder.Entity<CartItem>().HasRequired(x => x.Product).WithMany().Map(x => x.MapKey("ProductId"));
I am trying to ensure that whenever I retrieve a cartitem from the database there will be a join on the product table so I can access the product properties but not the other way around.
I basically want to be able to do:
string title = cartItem.Product.Title
using the configuration I have gives me an Object reference not set to an instance of an object exception.
Short answer: to solve your problem, make the Product property virtual.
In-depth:
First, you don't need a join to do this. EF works fine with lazy loading (you need the virtual modifier)
Second, you can fetch the Product eagerly, using the Include extension method. Example:
var cartItem = context.CartItems.Include(x => x.Product)
.Where(/*some condition*/).ToList();
...but you can't configure this to be the default behavior (nor is it a good idea usually)
Third, this is a many-to-one relationship, not one-to-one (a Product has many related CartItems)

EF 4.1 messing things up. Has FK naming strategy changed?

I've just installed the new Entity Framework 4.1 NuGet package, thus replacing the EFCodeFirst package as per NuGet intructions and this article of Scott Hanselman.
Now, imagine the following model:
public class User
{
[Key]
public string UserName { get; set; }
// whatever
}
public class UserThing
{
public int ID { get; set; }
public virtual User User { get; set; }
// whatever
}
The last EFCodeFirst release generated a foreign key in the UserThing table called UserUserName.
After installing the new release and running I get the following error:
Invalid column name 'User_UserName'
Which of course means that the new release has a different FK naming strategy. This is consistent among all other tables and columns: whatever FK EFCodeFirst named AnyOldForeignKeyID EF 4.1 wants to call AnyOldForeignKey_ID (note the underscore).
I don't mind naming the FK's with an underscore, but in this case it means having to either unnecessarily throw away the database and recreate it or unnecessarily renaming al FK's.
Does any one know why the FK naming convention has changed and whether it can be configured without using the Fluent API?
Unfortunately, one of the things that didn't make it to this release is the ability to add custom conventions in Code First:
http://blogs.msdn.com/b/adonet/archive/2011/03/15/ef-4-1-release-candidate-available.aspx
If you don't want to use the fluent API to configure the column name (which I don't blame you), then most straight forward way to do it is probably using sp_rename.
Why don't you do the following?
public class User
{
[Key]
public string UserName { get; set; }
// whatever
}
public class UserThing
{
public int ID { get; set; }
public string UserUserName { get; set; }
[ForeignKey("UserUserName")]
public virtual User User { get; set; }
// whatever
}
Or, if you don't want to add the UserUserName property to UserThing, then use the fluent API, like so:
// class User same as in question
// class UserThing same as in question
public class MyContext : DbContext
{
public MyContext()
: base("MyCeDb") { }
public DbSet<User> Users { get; set; }
public DbSet<UserThing> UserThings { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<UserThing>()
.HasOptional(ut => ut.User) // See if HasRequired fits your model better
.WithMany().Map(u => u.MapKey("UserUserName"));
}
}

Resources