Entity framework "Field required" Error but works fine in debuuging - entity-framework

I have got a strange error in entityframework when I am trying to update an entity which uses some virtual (lazy load) properties. I retrieve the entity from the database and change a one to one property in that then try to update it again.The exception for some of the virtual properties is The field is required while others don't have this error.
What makes everything even more strange is that when I try to inspect the entity in debug mode the code just works fine and I don't face any errors at all.
Has anyone else experienced such behavior?
Thanks
Here is what code looks like:
public class IndependenceCheck : ModelBase
{
[Key]
public int IndependenceCheckID { get; set; }
public int PrincipalCompanyID { get; set; }
[Required]
[ForeignKey("PrincipalCompanyID")]
public virtual Company PrincipalCompany { get; set; }
[ForeignKey("OrganizationAddressID")]
[Required]
public virtual Address OrganizationAddress { get; set; }
}
There are much more fields in model, while I try to update no errors for PrincipalCompany occurs but for OrganizationAddress I got the required field error.

Related

Invalid ColumnName, but ColumnName is correct (EFC)

So i'm trying to learn Design First EFC, but I have a problem getting Entities to work that have a many relationship with another Entity. I get this error message:SqlException: Invalid column name 'GuestListId'.
For experimentation I changed to the table into a one relationship. That works perfectly
This works:
public class GuestList
{
public Guid GuestListId { get; set; }
public Guest? Guest { get; set; }
}
However, when I want to have a many relationship, it does not work and fires the following errorcode: SqlException: Invalid column name 'GuestListId'.
This somehow does not work:
public class GuestList
{
public Guid GuestListId { get; set; }
public ICollection<Guest>? Guest { get; set; }
}
So I checked the GuestList table in SSMS, but that is identical to the entity in the sourcecode. I also updated the table but I still get the same problem. Does anyone have an idea what the problem is?
EDIT: So after a suggestion by someone, I added a GuestList property in Guest. But that still gives the same error:
public class Guest
{
public Guid GuestId { get; set; }
public string Name { get; set; }
public GuestList GuestList { get; set; }
}
So this is a picture of the sourcecode I have now that tries to insert data into the database.
Sourcecode
When I check the database, is see that GuestId value is not being assigned in the GuestList. But in the guest table I see that the GuestListid is being assigned:
Database Guest Table
Database GuestList Table
EDIT: I got it working now. As suggested, I migrated and updated my database. some tables have changed now. GuestList has only one column now and Guest has an extra column called GuestListId. See the pictures below:
enter image description here
enter image description here

EF Code First: Does not update foreign key constraint name when property is changed

I probably found a bug... at least it's annoying to me so I would appreciate if someone confirms this:
public int PriorityConfigurationSettingId { get; set; }
[ForeignKey("PriorityConfigurationSettingId")]
public virtual PriorityConfigurationSetting
PriorityConfigurationSetting{get;set; }
to
public int PriorityConfigurationSettingId { get; set; }
[ForeignKey("PriorityConfigurationSettingId")]
public virtual LookUp PriorityConfigurationSetting { get; set; }
When I change the name of a foreign key entity name from PriorityConfigurationSetting to LookUp. After done the model changes i try to get the script through EF Code Fist Migration, I didn't get any changes.

Value cannot be null. Parameter name: entitySet

I have a fairly standard setup with simply POCO classes
public class Project
{
public int ProjectId { get; set; }
public string Name { get; set; }
public int? ClientId { get; set; }
public virtual Client Clients { get; set; }
}
They use an interface
public interface IProjectRepository
{
IEnumerable<Project> Projects { get; }
}
and are constructed as a repository for ninject to bind to
public class EFProjectRepository : IProjectRepository
{
private EFDbContext context = new EFDbContext();
public IEnumerable<Project> Projects
{
get { return context.Projects; }
}
}
The actual context is a simply DbContext
public class EFDbContext : DbContext
{
public DbSet<Project> Projects { get; set; }
}
When I try and enable code first migrations I get the following error
I have done this exact process with other projects and there as never been an error. This is connecting to a local Sql Server Database. There does not seem to be a problem with the connection string. I have searched for this error online but the solutions seem to answer questions that do not directly relate to my setup.
I had the same issue and the cause was a POCO class that had a property of type Type.
Late to the game...but if it helps...
I had this same problem, everything was working fine, but this issue appeared, I added the following to one of my classes
public HttpPostedFileBase File { get; set; }
which seemed to break it.
I ensured I didn't map this to the database by using the following:
[NotMapped]
public HttpPostedFileBase File { get; set; }
You need to add the following using statement:
using System.ComponentModel.DataAnnotations.Schema;
Hope this helps
This problem can occur if one of the POCO classes was not declared in the DbContext.
I added them and the error went away
I had changed the name of the Task POCO class because of its association with a built in .NET name System.Threading.Tasks. However I had not changed this in the "TaskTimeLog" POCO where there was a relation. When going through the code the "Task" property in the "TaskTimeLog" POCO was not showing an error because it was now attached to that threading keyword and the reason I had changed the name in the first place.
I got this error:
Value cannot be null. Parameter name: entitySet
Turns out I was trying to join data from 2 different DbContexts.
var roles = await _identityDbContext.Roles
.AsNoTracking()
.Take(1000)
.Join(_configurationDbContext.Clients.ToList(),
a => a.ClientId,
b => b.Id,
(a,b) => new {Role = a, Client = b})
.OrderBy(x => x.Role.ClientId).ThenBy(x => x.Role.Name)
.Select(x => new RoleViewModel
{
Id = x.Role.Id,
Name = x.Role.Name,
ClientId = x.Role.ClientId,
ClientName = x.Client.ClientName
})
.ToListAsync();
The fix is to add ToList as shown. Then the join will happen in code instead of the database.
Only do this if you are OK with retrieving the whole table. (I know my "Clients" table will always be relatively small.)
For anyone not finding a resolution in the other answers, I got this error when I created a derived class from a class that had an instance in some model. The exception occurred on the first usage of my context in a request.
This is a stripped-down example that will reproduce the behaviour. Model is a DbSet in my context.
public class Model
{
public int Id { get; set; }
public Duration ExposureDuration { get; set; }
}
public class Duration
{
public int Value { get; set; }
public string Unit { get; set; }
}
//Adding this will cause the exception to occur.
public class DurationExtended : Duration
{ }
This happened during work in progress. When I changed the model property ExposureDuration to type DurationExtended, all was working again.
I had the same issue and it took quite a while to find out the solution.
In our case, we created a seperated project to handle the Entities and even if the default project in the Package Manager Console was the one handling the Entities, I need to set this project as the default project in order to make it work.
I hope this will help somebody else.
I got this error when I declared a variable of type Type - which is probably because is a complex type not supported by the DB.
When I changed it to string, the error went away
public class Sample
{
public int SampleID {get;set;}
public Type TypeInfo {get; set;} //This caused the error,
//because Type is not directly convertible
//in to a SQL datatype
}
I encountered this same issue and resolved like so:
Error in model class:
public class UserInformation
{
public string ID { get; set; }
public string AccountUserName { get; set; }
public HttpPostedFileBase ProfilePic { get; set; }
}
No error in model class
public class UserInformation
{
public string ID { get; set; }
public string AccountUserName { get; set; }
public string ProfilePicName { get; set; }
}
My issue was resolved once i updated the ProfilePic property type from HttpPostedFileBase to string. If you have a property that is not of type string, int, double or some other basic/standard type either replace such property or update to a type which SQL is more likely to accept.
Remove the line <Generator>EntityModelCodeGenerator</Generator> from your project file.
Check out this https://www.c-sharpcorner.com/UploadFile/5d065a/poco-classes-in-entity-framework/
I have some properties in "ExpenseModel", one of this was...
public virtual Type TypeId {get; set;}
which was causes the above same error because of "Type" propertyType,
so I changed "Type" => "ExpenseType" and it worked... :-)
public virtual ExpenseType TypeId {get; set;}
ExpenseModel.cs
public class ExpenseTypes
{
[Key]
public int Id { get; set; }
public string TypeName { get; set; }
public string Description { get; set; }
}
In my case I had to reference another model class called IanaTimeZone, but instead of
public virtual IanaTimeZone Timezone { get; set; }
out of rush I typed this:
public virtual TimeZone Timezone { get; set; }
and it compiled fine because VS thought it was System.TimeZone but EF6 was throwing the error. Stupid thing but took me a while to figure out, so maybe this will help someone.
To anyone else this might be helpful, I had a property TimeZone (the actual .NET TimeZone object) and this gave me the exact same error, not sure why but will dig deeper :)

Entity Framework Code first missing foreign key entities in WebAPI project

I'm afraid that if I include my code this post will get too long and too complicated, so I'll try and explain my problem. If however you'd like to see some code illustrating this problem, I'll be happy to add it afterwards.
I have a project, MVC4 project (Website.Web) that used entity framework code first. My entity classes is in a seperate project: Website.Domain
I have a NewsPost class:
public virtual int Id { get; set; }
public virtual string Subject { get; set; }
public virtual string Content { get; set; }
public virtual string ImageName { get; set; }
public virtual DateTime CreateTime { get; set; }
public virtual int CreatedById { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
And my comments class looks like this:
public virtual int Id { get; set; }
public virtual int CreatedById { get; set; }
public virtual DateTime CreatedTime { get; set; }
public virtual string Content { get; set; }
Now in my MVC project, I have entity framework set up with some repository classes and ninject to seperate everything from my controllers. And when I do a "GetAll()" on my newsposts. The NewsPost.Comments will be filled with the comments that's associated with this newspost. It all works perfectly.
Now I got the idea that I'd like to use webapi, so I set up a new MVC basic project. I removed the views folder, and removed the models folder. Then I setup all the repositories here as well along with my entity framework dbcontext class. And enabled migrations on the project to allow me to use entity framework code first in the same fasion as the Website.Web project. I also referenced the same Domain classes as the web project.
Now here comes the problems. I tried doing a GetAll() on the newsposts, but when I inspect the list returned by GetAll(), I see that though it fetches all the news in the database, the COMMENTS are null. I'm pretty sure I have the Website.API set up the same way as my Website.Website.Web - So what am I missing?
I hope I have explained well enough. Again if you need any additional code or I need to clarify some points, I'll happily do this, I just didn't wanna make the question more complicated than it already is with too much code.

Why does EF Code First [InverseProperty] attribute fail to work when used with [ForeignKey] attribute?

Using: EF 4.3.1, Visual Studio 2010, SQL CE 4.0
My understanding is that when declaring Foreign Keys with DataAnnotation in EF, it can be done either of the following ways:
Option 1-
[ForeignKey("Player1Home")]
public long? HPlayer1Id { get; set; }
public virtual Player Player1Home { get; set; }
Option 2-
public long? HPlayer1Id { get; set; }
[ForeignKey("HPlayer1Id")]
public virtual Player Player1Home { get; set; }
Problem:When the InverseProperty DataAnnotation gets used with Option 2 an extra column gets generated in the database (Player1Home_Id) in addition to HPlayer1Id.
[Table("Matches")]
public class Match
{
[Key]
public long Id { get; set; }
//-- Option 1 - THIS WORKS GREAT --//
public long? HPlayer1Id { get; set; }
[ForeignKey("HPlayer1Id")]
public virtual Player Player1Home { get; set; }
//-- Option 2 - THIS DOES NOT WORK, it generates an extra column in the database --//
[ForeignKey("Player1Home")]
public long? HPlayer1Id { get; set; }
public virtual Player Player1Home { get; set; }
}
[Table("Players")]
public class Player
{
[Key]
public long Id { get; set; }
[InverseProperty("Player1Home")]
public virtual ICollection<Match> MatchesAsHome1 { get; set; }
}
Of course if I rename HPlayer1Id to Player1HomeId, then Option 2 works correctly again. But the whole purpose of the DataAnnotation is to allow explicit naming when 'Conventions' cannot automatically determine the matching property.
Removing the InverseProperty DataAnnotation on the Player class also seems to fix the issue, but unfortunately I cannot do this because my actual Match class has four Players in it, and thus I need explicit mappings.
And finally, I know I can just use Option 1, but I prefer the consistency of declaring all of my Keys (Primary and Foreign) on the Id fields rather than Foreign Keys on Navigation Properties. And technically, either way is supposed to work.
Is this just a bug in 4.3.1? In EF Code first?
Or is Mapping a ForeignKey AND an InverseProperty from two different properties to a common third property not supported?
Any information would be greatly appreciated!
Update: a second bug?
A third option should work as well (as suggested by Slauma), but causes a NullReferenceException to be thrown the first time I attempt to add an entity to the database. The database never ends up getting created, whereas Option 2 from above does not have this issue. It appears this has worked for Slauma on EF 4.1, but does not for me with EF 4.3.1. (I'm using it with SQL CE 4.0)
[Table("Matches")]
public class Match
{
[Key]
public long Id { get; set; }
[ForeignKey("Player1Home")]
public long? HPlayer1Id { get; set; }
[InverseProperty("MatchesAsHome1")]
public virtual Player Player1Home { get; set; }
}
[Table("Players")]
public class Player
{
[Key]
public long Id { get; set; }
public virtual ICollection<Match> MatchesAsHome1 { get; set; }
}
public class MyContext : DbContext
{
public DbSet<Match> Matches { get; set; }
public DbSet<Player> Players { get; set; }
}
Usage:
try
{
MyContext mc = new MyContext();
//NullReferenceException gets thrown on the next call
mc.Matches.Add(new Match());
mc.SaveChanges();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
This was fixed in EF5 and I've confirmed it still behaves correctly in EF6.
You can see notes of investigation on this issue - https://entityframework.codeplex.com/workitem/138.
Same behaviour in EF 4.1.
You didn't mention the option to move the InverseProperty attribute to the other side of the relationship:
[Table("Matches")]
public class Match
{
[Key]
public long Id { get; set; }
[ForeignKey("Player1Home")]
public long? HPlayer1Id { get; set; }
[InverseProperty("MatchesAsHome1")]
public virtual Player Player1Home { get; set; }
}
[Table("Players")]
public class Player
{
[Key]
public long Id { get; set; }
public virtual ICollection<Match> MatchesAsHome1 { get; set; }
}
This worked for me and didn't create the extra column.
The behaviour of your option 2 looks like a code-first bug to me.
Edit
Confirming that changing the version from EF 4.1 to EF 4.3.1 causes a NullReferenceException with the model above. The database doesn't get created.