Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I got this error when I tried to save a Response model object into the database by executing this line:
_context.Add(response);
await _context.SaveChangesAsync(); <-- Exception happens in here
The RequestId column in Response table is a foreign key referenced from Request table.
CreateRequestViewModel is the view model I created based on Request model but only have the fields required user to fill in to create a Request.
CreateResponseViewModel is the view model I created based on Response model but only have the fields required user to fill in to create a Response.
The database models are generated using command:
Scaffold-DbContext "Data Source=localhost;Initial Catalog=Test;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
I mapped the value from CreateResponseViewModel object to Response model object in controller action method and tried to save into database, but got this error. My guessing it may be related to cascading update/insert in the Entity Framework Core, but have no idea how to fix it.
Any help would be appreciated. Thank you.
Generally speaking, that error occurs when your entities are out of sync with your database. Based on the current state of your entity classes, Entity Frameworks thinks there should be a column named CreateRequestViewModelRequestId, but that column does not actually exist in the table. Short answer is that you need to run a migration to update the database.
However, it's not at all clear what you're doing here and nothing with ViewModel at the end of the class name should ever be going into your database. I imagine you have much deeper issues here that will need to be solved.
The problem is caused by adding these two lines in the Context class:
public virtual DbSet<CreateRequestViewModel> CreateRequest { get; set; }
public virtual DbSet<CreateResponseViewModel> CreateResponse { get; set; }
Chris is right, ViewModel should not go into database. After remove these 2 lines, it works as expected.
Related
I might be not getting how some stuff work in Blazor, but here's what my issue is:
whenever I want to edit an object for example People object, I select it in #page "/people" from a table, then I'm redirected to the #page "people/edit/id". In #page "people/edit" I have an EditForm with InputText corresponding to the people model and the #bind value, everything is normal, it loads the data correctly.
The problem is when I edit some of the inputs and not save the data, just modify its values, and then go back to the #page "people", or anywhere, the object is modified.
I even put a breakpoint to watch the object being pulled from the database through Entity Framework Core, and it shows the modified version too, but checking on the database table, it does not seem to be affected.
It sounds impossible, but I tried with brand new projects, or others people projects in video tutorials, try replicating and does the same thing, so what's the deal here?
#page "/People/edit{id}"
#code {
[Parameter] public string id { get; set; }
Person person = new Person();
protected override async Task OnParametersSetAsync()
{
person = await PersonService.GetByIdAsync(id);
}
}
Firstly, if you put some object as a model for an EditForm and make some changes to it, all changes are reflected in the object immediately, but not after you click a submit.
Secondly, when you pull an object from a database it gets attached to the DbContext and stays attached, unless you detach it explicitly. When you query the entity, already attached to the context, the context does not query the database again, but gives you the attached entity. And if you have made some changes to it, you get these changes.
But those changes are not saved to database until you execute context.SaveChanges, so when you see the actual database, you see the unchanged data.
The difference with Net Core MVC is that Net Core MVC is stateless. Though you use references to the .NET objects in .cshtml files, they are used only during one query and get destroyed after the response is sent to client. When you use Blazor, you get actual .NET runtime ether on server (Blazor server) or on client (Blazor wasm), so your objects remain and preserve their state.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Ok, I am trying to make a record and send an email notification/acknowledgement that the record has been recorded. I have a many to many relationship between a Players model and a Lessonhours model. The User model has a one to many with the Players model.
I have run my 'store' method with several different modifications and I finally get my email to send. The problem is that I can't get the array of players that exist and send each an email. The multiple selections from my form are being properly inserted in their respective tables. When it comes to collecting the email data, I have come closest with the following code. The problem with THIS is that I only get one player instead of two or more when they exist. I hope this makes sense. Screenshots below.
Code and screenshot of $request array:
Players Model:
I am not very experienced with this and I am finding it difficult to pinpoint which documentation example to use. How can I get all of the emails addresses for sending after the insertion of record? I appreciate all help offered.
Lessonhours Model:
Store Lessonhours form
User Model
I'm not sure why you're putting an array inside an array for whereIn clause but if request players is already coming through as an array then your should just be able to do:
whereIn('id', $request->players)
Next you're only ever going to be sending one email because you're returning from inside the loop so it's going to send the first player one email and then return a response. To save have a temporary variable that you're not using again you could do:
Players::with('users')->whereIn('id', $request->players)->get()
->each(function ($player) use ($lesshours) {
Mail::to($player->users)->send(new ThankYouForLessonPackagePurchase($lesshours));
});
return back()->with(['success' => 'Player is enrolled in new Lesson Package.']);
You don't have to do the above it's just another way to write it.
Lastly, if you're always going to require player ids to be sent then you might as well add it to the validation array:
'players => 'required',
'players.*' => 'exists:players,id',
Hope this helps!
Edit: This is not a problem with ignorance of basic programming (such as trying to dereference a null object reference).
Edit: Added the stack trace from EF within Linqpad.
Using EF6, I have a very simple query :
var menu = dbcontext.Tree.Where(t => t.Left > 2 && t.Right < 10).ToList();
This worked right up until it mysteriously stopped. dbcontext.Tree is a view in SQL Server 2012. Using Linqpad5, I get the results I expect using its built-in connection. Setting up an EF connection to my project, I get the NRE. Checking the SQL, I can copy and paste that into a SQL query window and get the proper results. I get an NRE without the Where call, also.
I've tried updating my model from database to refresh anything. I've tried removing the view from the model and updating. I've tried deleting the model entirely and recreating it. I've restarted Visual Studio AND my computer. I get the same NRE for the query. I don't know what else I can try, and this NRE makes no sense to me at all, given I get the results I expect using everything but EF. I'd chalk it up to a bug with EF if I didn't see it working previously.
Has anyone dealt with this? Searching online for this specific set of circumstances has produced nothing.
Stack Trace :
at System.Data.Entity.Core.EntityKey.AddHashValue(Int32 hashCode, Object keyValue)
at System.Data.Entity.Core.EntityKey.GetHashCode()
at System.Collections.Generic.GenericEqualityComparer`1.GetHashCode(T obj)
at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
at System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
at System.Data.Entity.Core.Objects.ObjectStateManager.TryGetEntityEntry(EntityKey key, EntityEntry& entry)
at System.Data.Entity.Core.Objects.ObjectStateManager.FindEntityEntry(EntityKey key)
at System.Data.Entity.Core.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly[TEntity](Func`2 constructEntityDelegate, EntityKey entityKey, EntitySet entitySet)
at lambda_method(Closure , Shaper )
at System.Data.Entity.Core.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper)
at System.Data.Entity.Core.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext()
at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
The problem is that your Model (Tree in your example above) has one ore more properties that are not nullable (and possibly also marked as not nullable in the mapping) but the corresponding column in the data store is nullable. This exception would only manifest itself as soon as there was a record being retrieved that had a null value for one of those column(s).
Model fix - When updating the model be sure to use Nullable<T> or ? for nullable value types and if you have mappings defined (either via attributes or in types that inherit EntityTypeConfiguration) also specify that the property is optional there.
Data store fix - Alternatively change the data store schema and data to align it with what is expected in the model.
I have a simple entity class in a WPF application that essentially looks like this:
public class Customer : MyBaseEntityClass
{
private IList<Order> _Orders;
public virtual IList<Order> Orders
{
get { return this._Orders; }
set {this._Orders = new ObservableCollection<Order>(value);}
}
}
I'm also using the Fluent automapper in an offline utility to create an NHibernate config file which is then loaded at runtime. This all works fine but there's an obvious performance hit due to the fact that I'm not passing the original collection back to NHibernate, so I'm trying to add a convention to get NHibernate to create the collection for me:
public class ObservableListConvention : ICollectionConvention
{
public void Apply(ICollectionInstance instance)
{
Type collectionType =
typeof(uNhAddIns.WPF.Collections.Types.ObservableListType<>)
.MakeGenericType(instance.ChildType);
instance.CollectionType(collectionType);
}
}
As you can see I'm using one of the uNhAddIns collections which I understand is supposed to provide support for both the convention and INotification changes, but for some reason doing this seems to break lazy-loading. If I load a custom record like this...
var result = this.Session.Get<Customer>(id);
...then the Orders field does get assigned an instance of type PersistentObservableGenericList but its EntityId and EntityName fields are null, and attempting to expand the orders results in the dreaded "illegal access to loading collection" message.
Can anyone tell me what I'm doing wrong and/or what I need to do to get this to work? Am I correct is assuming that the original proxy object (which normally contains the Customer ID needed to lazy-load the Orders member) is being replaced by the uNhAddIns collection item which isn't tracking the correct object?
UPDATE: I have created a test project demonstrating this issue, it doesn't reference the uNhAddins project directly but the collection classes have been added manually. It should be pretty straightforward how it works but basically it creates a database from the domain, adds a record with a child list and then tries to load it back into another session using the collection class as the implementation for the child list. An assert is thrown due to lazy-loading failing.
I FINALLY figured out the answer to this myself...the problem was due to my use of ObservableListType. In NHibernate semantics a list is an ordered collection of entities, if you want to use something for IList then you want an unordered collection i.e. a Bag.
The Eureka moment for me came after reading the answer to another StackOverflow question about this topic.
I am developing an ASP.Net MVC 4 web application with Entity Framework 5.0 for data persistence. I am using Code First and Automatic Migrations during development.
As I had to work with an existing database I used this helpful tutorial to create my Domain Classes
Code First to an Existing Database
I have a class in my model named tblcourseapplicant which has a String property called ManagerTitle. I would like to change this datatype to Int, and to do this I changed the property in the POCO class
from
public string ManagerTitle { get; set; }
to
public int ManagerTitle { get; set; }
and then I changed the property attribute in the relevant Mapping Class (tblcourseapplicantMap) using Fluent API
from
this.Property(t => t.ManagerTitle).HasMaxLength(5);
to
this.Property(t => t.ManagerTitle).IsRequired();
I also updated all the data in the database for this particular column so that all the values were converted to integers.
I ran my project and the automatic migrations try to perform this update for me, but it comes back with the following error
Cannot insert the value NULL into column 'ManagerTitle', table
'tblcourseapplicant'; column does not allow nulls. UPDATE fails. The
statement has been terminated.
I can't understand why this is, as there are no records in my database table where ManagerTitle is NULL, they have all been assigned an integer value.
Any help would be greatly appreciated.
Thanks.
UPDATE
Folks I am still struggling to find a solution to this problem. I noticed that the error coming back is an SqlException. Does anyone have any ideas please? I don't understand what the problem is here, my understanding is that Code First Automatic Migrations should be able to handle this simple property datatype change.
Help!
Has the column been defined as nullable in the database?
You can also try making it nullable in the POCO
public int? ManagerTitle { get; set; }
When doing a similar update with non-Automatic Migrations the update code would just delete the old column and create a new one without any data migration between renamed (or retyped) properties.
I suspect this might be the case with your issue.