EntityCommandExecutionException - Trying to link 2 models in 1 database [duplicate] - c#

This question already has answers here:
There is already an open DataReader associated with this Command which must be closed first
(19 answers)
Closed 6 years ago.
Pretty much I have 2 models - A announcement where some can post an announcement and a seen model which determins if someone has seen the announcement. her eis the models:
Announce:
public class Announcement
{
public int AnnouncementId { get; set; }
public string AnnouncementContent { get; set; }
public virtual ApplicationUser User { get; set; }
}
and Seen:
public class Seen
{
public int SeenId { get; set; }
public virtual Announcement Announcement { get; set; }
public virtual ApplicationUser User { get; set; }
}
in my AnnouncementController.Index I have this code which pretty much supposed to be, if you view this page, mark off every announcement as seen bbut am getting errors at the "new seen" part:
public ActionResult Index()
{
string currentUserId = User.Identity.GetUserId();
var currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);
if(db.Announcements != null)
{
foreach (Announcement anoun in db.Announcements)
{
new Seen
{
User = db.Users.Add(currentUser),
Announcement = db.Announcements.FirstOrDefault(x => x.AnnouncementId == anoun.AnnouncementId),
};
}
}
return View(db.Announcements.ToList());
}
There is already an open DataReader associated with this Command which must be closed first.
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public DbSet<Announcement> Announcements { get; set; }
public DbSet<Comment> Comments { get; set; }
public DbSet<Seen> Seens { get; set; }
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}

Event if you did not have that error, you still have other issues. See below:
public ActionResult Index() {
string currentUserId = User.Identity.GetUserId();
var currentUser = db.Users.FirstOrDefault( x => x.Id == currentUserId );
List<Seen> seens = new List<Seen>();
if( db.Announcements != null ) {
foreach( Announcement anoun in db.Announcements ) {
seens.Add(
new Seen
{
User = currentUser, // You have this already so why go to the database again?
Announcement = anoun, // Same with this.
});
}
}
// Save seens to the database
return View( db.Announcements.ToList() );

The error is because you are actively iterating over a collection streaming from the database and then trying to re-issue another select to the database inside that loop. It can be fixed by forcing the materialization of the collection before you enter the loop using ToList() (other options are also available like AsEnumerable or ToArray).
foreach (Announcement anoun in db.Announcements.ToList())
{
new Seen
{
User = db.Users.Add(currentUser),
Announcement = db.Announcements.FirstOrDefault(x => x.AnnouncementId == anoun.AnnouncementId),
};
}
That being said I am not sure why you are doing it this way. Why not attach the instance anoun directly as you are only using a single (or same in the code shown) DbContext instance (variable named db).
foreach (Announcement anoun in db.Announcements)
{
new Seen
{
User = currentUser, // also this seemed wrong before, just assign the reference directly
Announcement = anoun
};
}
Or make it even more simple:
var newSeens = db.Announcements.Select(x => new Seen(){User = currentUser, Announcement = x}).ToList();
db.Seens.AddRange(newSeens);
db.SaveChanges();
This assumes that the user has not seen any announcement. If the user has seen some then you need to filter db.Announcements on existing Seen records for that user.

Related

User defined order using EF and Postgresql

I have a category model class with category name, Id and admin order properties.
I want to provide an API endpoint to admin to reorder the categories as per his need.
I am not sure what is the most efficient way to tackle this using the EF Core and Postgresql (Core 2.2) - I'm a newbie to C# and .NET Core. Please correct me if my approach is wrong.
Here is what I tried:
My model class:
public class Category
{
public string Name { get; set; }
public int Id { get; set; }
public int adminOrder { get; set; }
}
I have my service repository as below with GetCategories and UpdateCategories methods:
public class CategoryRepository: ICategoryRepository
{
private ApplicationDbContext _categoryContext
public CategoryRepository(ApplicationDbContext categoryContext)
{
__categoryContext = _categoryContext
}
public ICollection<Category> GetCategories()
{
return _categoryContext.Categories.OrderBy(c=> c.Name).ToList();
}
public bool UpdateCategoryOrder(Category category)
{
_categoryContext.Update(category);
return Save();
}
public bool Save()
{
var changesMade = _categoryContext.SaveChanges();
return changesMade >= 0 ? true : false;
}
}
In my controller I am taking the list of categories in request body and comparing them with existing categories on field adminOrder.
If they are not equal I am updating the database
public IActionResult UpdateCategory([FromBody] List < Category > categoriesList)
{
var existingList = _categoryRepository.GetCategories();
foreach(var cat in categoriesList)
{
if (existingList.Where(c => c.Id == cat.Id && c.adminOrder != cat.adminOrder)
{
_categoryRepository.UpdateCategory(cat) // since it returns true I can use if statement to check if it fails
}
}
}
I am not sure it is the right way to do or not.
I went through few docs like
https://dba.stackexchange.com/questions/201898/user-defined-ordering-in-sql
https://begriffs.com/posts/2018-03-20-user-defined-order.html
Not sure how to implement them in EF

Unable to get Namespace from ObjectStateEntry when saving from a ViewController

I'm attempting to create an Audit Log for my MVC, Entity Framework website project. I've been able to subscribe to SaveChanges() in my DBContext (and save to my database through another DBContext but same database).
My two questions in the end are:
What does if (!entry.IsRelationship) do exactly? I have a ViewModel that calculates this as True when Saving and another as False. I would expect this to move into the rest of my method to save in the Audit Log.
How can I get the full Namespace of my Object being modified? I was using this: entry.Entity.ToString() but doesn't seem to work when Saving/Editing from a View Model (details below)
Here is a basic setup that I have thus far (Album object/controller works, but AlbumView doesn't):
Ablum class:
public class Album : BaseObject //BaseObject has a few properties, one is Oid (Guid)
{
public string Name { get; set; }
[Column(TypeName = "varchar(MAX)")]
[DataType(DataType.MultilineText)]
public string Description { get; set; }
[Display(Name="Genres")]
public virtual ICollection<AlbumsGenres> AlbumGenres { get; set; }
[Display(Name="Artists")]
public virtual ICollection<AlbumsArtists> AlbumArtists { get; set; }
}
AblumView class:
public class AlbumView
{
[ScaffoldColumn(false)]
public Guid Oid { get; set; }
[Required]
public string Name { get; set; }
[Column(TypeName = "varchar(MAX)")]
[DataType(DataType.MultilineText)]
public string Description { get; set; }
[Display(Name = "Genres")]
public virtual List<AlbumsGenres> AlbumGenres { get; set; }
[Display(Name = "Artists")]
public virtual List<AlbumsArtists> AlbumArtists { get; set; }
}
AlbumsController (Audit works with something like this):
public ActionResult Edit(Album album)
{
if (ModelState.IsValid)
{
db.Entry(album).State = EntityState.Modified;
db.SaveChanges(); //This is where SaveChanges() takes over (see below)
return RedirectToAction("Index");
}
return View(album);
}
AlbumsViewController:
public ActionResult Edit(Guid id, AlbumView albumViewModel)
{
//Omitting setup...
//Album gets updated
Album album = db.Albums.Find(id);
album.Name = albumViewModel.Name;
album.Description = albumViewModel.Description;
//Other Objects are also updated, just an example:
albumArtists = new AlbumsArtists();
albumArtists.Oid = Guid.NewGuid();
albumArtists.Album = db.Albums.Find(id);
albumArtists.Artist = db.Artists.Find(item.Artist.Oid);
//In the end it calls:
db.SaveChanges();
//Omitting other stuff...
}
On db.SaveChanges() within my DbContext:
public class ApplicationDBContext : DbContext
{
public ApplicationDBContext() : base("name=DefaultConnection") { }
public System.Data.Entity.DbSet<ContentPub.Models.Music.Album> Albums { get; set; }
//Other DBSet objects...
public DbSet Set(string name)
{
return base.Set(Type.GetType(name));
}
public override int SaveChanges()
{
ApplicationLogDBContext logDb = new ApplicationLogDBContext();
ChangeTracker.DetectChanges();
ObjectContext ctx = ((IObjectContextAdapter)this).ObjectContext;
List<ObjectStateEntry> objectStateEntryList =
ctx.ObjectStateManager.GetObjectStateEntries(EntityState.Added
| EntityState.Modified
| EntityState.Deleted)
.ToList();
foreach (ObjectStateEntry entry in objectStateEntryList)
{
Guid oid = Guid.Empty;
try
{
if (!entry.IsRelationship) //I don't understand this (first of my two questions)
{
switch (entry.State)
{
//Removed other cases
case EntityState.Modified:
{
oid = (Guid)entry.EntityKey.EntityKeyValues[0].Value;
//This is the area that I am having issues (second of the two questions)
//Below will work when I call db.SaveChanges() from the AlbumsController,
//'entry.Entity.ToString()' will get 'x.Models.Music.Albums' and begin a query
var query = this.Set(entry.Entity.ToString()).AsNoTracking().Where("Oid == #0", oid);
//The issue with the above is when I have a ViewModel, returns something like
// = System.Data.Entity.DynamicProxies.Album_AF81C390156ACC8283ECEC668AFB22C4AD621EF70F8F64641D56852D19755BF3
//If the proper Namespace is returned, the next line works and Audit continues
var query = this.Set(entry.EntitySet.ElementType.ToString()).AsNoTracking().Where("Oid == #0", oid);
//Does a bunch of AuditLog stuff if the above issue doesn't fail
break;
}
}
}
}
catch (Exception ex)
{
throw new Exception("Log Error (" + entry.Entity.ToString() + ") - " + ex.ToString());
}
}
return base.SaveChanges();
}
}
entry.Entity.ToString() will return something like:
System.Data.Entity.DynamicProxies.Album_AF81C390156ACC8283ECEC668AFB22C4AD621EF70F8F64641D56852D19755BF3
In the AlbumView I am updating Album, and a bunch of other Objects. Not sure why it isn't returning x.Models.Music.Albums, is there a work-around, can someone explain or point me to other resources that I haven't found yet?
While it isn't the most efficient solution, it still is a solution for now.
I was able to do the following inside my db.SaveChanges() method:
//When AlbumView .BaseType was able to return x.Models.Music.Album
string strNamespace = entry.Entity.GetType().BaseType.ToString();
//Needed this if I was updating just an Object (ie: Album),
//would be nice to make something more concret
if (strNamespace == "x.Models.Core.BaseObject")
strNamespace = entry.Entity.ToString();
//Continuing code
var query = this.Set(strNamespace).AsNoTracking().Where("Oid == #0", oid);
Found the answer here from another Question that I had not found before posting this question

Copying data between models and saving children without entities duplicating themselves in Entity Framework

I am having trouble saving children entities via Entity Framework / ASP Identity. It seems to be adding duplicates of everything that is added.
I have tried using a detached graph of the DrivingLicenceModel by TeamMember.DrivingLicence = null in the TeamMemberModel and then working with a detached graph by looking if there is new or old DrivingLicenceCategories but because DrivingLicence links back to TeamMember it causes TeamMember.DrivingLicenceId to be null as it cannot link back to TeamMember.
I have tried Manually adding the EntityState to the DrivingLicence and DrivingLicenceCategories but when I do that it complains that it cannot save two entities with the same primary key.
I assume this is because they way I am copying the entities but I after a lot of looking I am drawing a blank.
If there anyway to copy from TeamMemberRequestModel to TeamMemberModel and then save without the children trying to create clone copies of themselves?
Models
public class TeamMemberModel : IdentityUser
{
public virtual DrivingLicenceModel DrivingLicence { get; set; }
public void ShallowCopy(TeamMemberRequestModel src)
{
this.DateOfBirth = src.DateOfBirth;
if (src.DrivingLicence != null)
{
if (this.DrivingLicence == null)
{
this.DrivingLicence = new DrivingLicenceModel(src.DrivingLicence);
}
else
{
this.DrivingLicence.ShallowCopy(src.DrivingLicence);
}
}
}
public TeamMemberModel() { }
}
public class DrivingLicenceModel
{
[Key]
public int Id { get; set; }
[ForeignKey("TeamMember")]
public string TeamMemberId { get; set; }
[JsonIgnore]
public TeamMemberModel TeamMember { get; set; }
public virtual List<DrivingLicenceCategoryModel> DrivingLicenceCategories { get; set; }
public DrivingLicenceModel() { }
public DrivingLicenceModel(DrivingLicenceModel src)
{
this.ShallowCopy(src);
}
public void ShallowCopy(DrivingLicenceModel src)
{
this.Id = src.Id;
this.IsFullLicence = src.IsFullLicence;
this.IssueDate = src.IssueDate;
this.ExpiryDate = src.ExpiryDate;
this.IssuingAuthority = src.IssuingAuthority;
this.LicenceNumber = src.LicenceNumber;
this.DrivingLicenceCategories = src.DrivingLicenceCategories;
this.DrivingLicencePoints = src.DrivingLicencePoints;
}
}
public class DrivingLicenceCategoryModel
{
[Key]
public int Id { get; set; }
[ForeignKey("DrivingLicence")]
public int DrivingLicenceId { get; set; }
[JsonIgnore]
public DrivingLicenceModel DrivingLicence { get; set; }
}
public class TeamMemberRequestModel
{
public string Id { get; set; }
public virtual DrivingLicenceModel DrivingLicence { get; set; }
}
Context
public class TIERDBContext : IdentityDbContext<TeamMemberModel, RoleModel, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>
{
public TIERDBContext() : base("SARDBConnection") { }
public DbSet<DrivingLicenceModel> DrivingLicences { get; set; }
public DbSet<DrivingLicenceCategoryModel> DrivingLicenceCategories { get; set; }
}
Controller
public async Task<IHttpActionResult> Put(string id, TeamMemberRequestModel teamMember)
{
TeamMemberModel CurrentTeamMember = await this.TIERUserManager.FindByIdAsync(id);
CurrentTeamMember.ShallowCopy(teamMember);
await this.TIERUserManager.UpdateAsync(CurrentTeamMember);
}
you have to create clone property into context class
.
In the context clases you could to use clone method that retiran the entity you send by parameters this duplicarse any entity you pass. Sorry for my english
hope you help
After far to many hours working over this. I have come to an answer. The best way to deal with this is to simply deal with it is to add or attach all entities down the tree.
The controller now attaches all children unless they have an ID of 0, therefore new and uses add instead. Then I use this very useful extension I found here http://yassershaikh.com/c-exceptby-extension-method/ to compare lists to see added and deleted entities in the list. While I don't need the added part as the entity will already be marked to an add state as I use add() it does not harm and I want to use it later with add and delete state changing.
Controller
public async Task<IHttpActionResult> Put(string id, TeamMemberRequestModel teamMember)
{
TIERDBContext IdentityContext = (TIERDBContext)this.TIERUserManager.UserStore().Context;
foreach (DrivingLicenceCategoryModel DrivingLicenceCategory in teamMember.DrivingLicence.DrivingLicenceCategories)
{
if (DrivingLicenceCategory.Id == 0)
{
IdentityContext.DrivingLicenceCategories.Add(DrivingLicenceCategory);
}
else
{
IdentityContext.DrivingLicenceCategories.Attach(DrivingLicenceCategory);
}
}
foreach (DrivingLicencePointModel DrivingLicencePoint in teamMember.DrivingLicence.DrivingLicencePoints)
{
if (DrivingLicencePoint.Id == 0)
{
IdentityContext.DrivingLicencePoints.Add(DrivingLicencePoint);
}
else
{
IdentityContext.DrivingLicencePoints.Attach(DrivingLicencePoint);
}
}
this.DetectAddedOrRemoveAndSetEntityState(CurrentTeamMember.DrivingLicence.DrivingLicenceCategories.AsQueryable(),teamMember.DrivingLicence.DrivingLicenceCategories, IdentityContext);
this.DetectAddedOrRemoveAndSetEntityState(CurrentTeamMember.DrivingLicence.DrivingLicencePoints.AsQueryable(),teamMember.DrivingLicence.DrivingLicencePoints, IdentityContext);
CurrentTeamMember.ShallowCopy(teamMember);
await this.TIERUserManager.UpdateAsync(CurrentTeamMember);
}
I then use a generic that uses ExceptBy to work out what is added and delete from the old team member model to the new team member model.
protected void DetectAddedOrRemoveAndSetEntityState<T>(IQueryable<T> old, List<T> current, TIERDBContext context) where T : class, IHasIntID
{
List<T> OldList = old.ToList();
List<T> Added = current.ExceptBy(OldList, x => x.Id).ToList();
List<T> Deleted = OldList.ExceptBy(current, x => x.Id).ToList();
Added.ForEach(x => context.Entry(x).State = EntityState.Added);
Deleted.ForEach(x => context.Entry(x).State = EntityState.Deleted);
}
It works but it is far from great. It takes two DB queries, getting the original and updating. I just cannot think of any better way to do this.

How to update a collection inside an entity within a post action in ASP.NET MVC5?

I have created an ASP.NET MVC5 sample project. I created my entities and from that, scaffolded the controllers for CRUD operations. I can only edit the POD members with the scaffolded code. I want to be able to add/remove related entities.
With my current code, when I click save there is no error but no related entities are modified (POD data is modified though). For example, if I wanted to remove all players from the account, they aren't removed. What am I doing wrong?
How can I remove/add related entities and push those changes to the database?
Here is the form:
Here is the action to update the entity:
public async Task<ActionResult> Edit([Bind(Include = "Account,Account.AccountModelId,Account.Name,Account.CreatedDate,SelectedPlayers")] AccountViewModel_Form vm){
if (ModelState.IsValid){
if (vm.SelectedPlayers != null){
vm.Account.PlayerModels = db.PlayerModels.Where(p => p.AccountModel.AccountModelId == vm.Account.AccountModelId).ToList();
foreach (var player in vm.Account.PlayerModels){
player.AccountModel = null;
db.Entry(player).State = EntityState.Modified;
}
vm.Account.PlayerModels.Clear();
foreach (var player_id in vm.SelectedPlayers){
var player = db.PlayerModels.Where(p => p.PlayerModelId == player_id).First();
vm.Account.PlayerModels.Add(player);
db.Entry(player).State = EntityState.Modified;
}
}
db.Entry(vm.Account).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(vm);
}
Here are the models:
public class AccountViewModel_Form{
public AccountModel Account { get; set; }
public HashSet<Int32> SelectedPlayers { get; set; }
public virtual List<PlayerModel> PlayersList { get; set; }
}
public class AccountModel{
public AccountModel(){
PlayerModels = new HashSet<PlayerModel>();
}
public Int32 AccountModelId { get; set; }
public string Name { get; set; }
public DateTime CreatedDate { get; set; }
public virtual ICollection<PlayerModel> PlayerModels { get; set; }
}
public class PlayerModel{
public Int32 PlayerModelId { get; set; }
public float Gold { get; set; }
public string Name { get; set; }
public virtual AccountModel AccountModel { get; set; }
}
I'm basically lost. I can't find any examples in how to update related data. Could someone point me in the right direction?
I come from Symfony (PHP Framework) background. I thought it would be easier but I have been having problems.
Basically I was missing the Attach function and that I had to force the load on the collection to make it work.
I found how to attach a non-attached entity here: Model binding in the controller when form is posted - navigation properties are not loaded automatically
When you post the data, the entity is not attached to the context, and when you try to save changes to a complex entity, the context makes a mess.
The code is a little different because I was trying to make it work at home. But it is essentially the same models.
public ActionResult Edit(AccountEditViewModel vm)
{
if (ModelState.IsValid)
{
//I was missing these 2 important lines...
db.Accounts.Attach(vm.Account);
db.Entry(vm.Account).Collection(a => a.Players).Load();
if (vm.SelectedPlayers != null)
{
foreach (var player in vm.Account.Players.ToList())
{
if (vm.SelectedPlayers.Contains(player.Id) == false)
{
player.Account = null;
vm.Account.Players.Remove(player);
db.Entry(player).State = EntityState.Modified;
vm.SelectedPlayers.Remove(player.Id);
}
}
foreach (var player_id in vm.SelectedPlayers)
{
var player = db.Players.Where(p => p.Id == player_id).First();
player.Account = vm.Account;
vm.Account.Players.Add(player);
db.Entry(player).State = EntityState.Modified;
}
}else
{
vm.Account.Players.Clear();
}
db.Entry(vm.Account).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(vm);
}

"Sequence contains no matching element" on ToList()

I have a piece of code that should retrieve a List of User objects.
public List<User> GetUsersBySessions(string[] sessionStrs, string ip)
{
if (sessionStrs == null || string.IsNullOrEmpty(ip))
return new List<User>();
using (var ctx = new DataContext())
{
var ret = ctx.Sessions.Include("User").Where(s => sessionStrs.Contains(s.ID) && s.IP.Equals(ip)).Select(s => s.User).ToList();
return ret;
}
}
The arguments sessionStrs and ip are properly passed into the method. However, I'm getting the following error:
(source: imgbomb.com)
How could this type of error be caused when I'm not using any .First() or .Single()? I'm just trying to get all items in a table that fit into an array return them as a List. I've never seen such a problem before.
The following line of code even causes an error:
var ret = ctx.Sessions.ToList();
Here is my DataContext:
public class DataContext : DbContext
{
public GenericDataContext()
: base(CONNECTION_STRING) //My CONNECTION_STRING is defined somewhere else, but I'm going to hide that for security's sake.
{
}
public DbSet<Password> Passwords { get; set; }
public DbSet<Session> Sessions { get; set; }
public DbSet<User> Users { get; set; }
}
And here is my Session model:
[Table("tbl_Sessions")]
public class Session
{
[Column("SessionID")]
[MaxLength(24)]
[Required]
[Key]
public string ID { get; set; }
[Column("UserID")]
[Required]
public int UserID { get; set; }
[Column("IP")]
[MaxLength(24)]
[Required]
public string IP { get; set; }
[ForeignKey("UserID")]
public virtual User User { get; set; }
}
NOTE
Both Classes are properly namespaced and have their proper using statements, as well.
The actual answer to this question had to do with the fact that one of my models had two Keys, each of which was a string. When I changed said model to have an int as it's Key, all worked well.
May be sessionStrs is null:
public List<User> GetUsersBySessions(string[] sessionStrs, string ip)
{
using (var ctx = new DataContext())
{
var ret = ctx.Sessions.Include("User");
if(sessionStrs!=null && sessionStrs.Any())
ret =ret.Where(s => sessionStrs.Contains(s.ID));
if(!string.IsNullOrEmpty(ip))
ret =ret.Where(s => s.IP.Equals(ip));
return ret.Any()?ret.Select(s => s.User).ToList():NULL;
}
}
Try to check if you have elements before selecting:
var ret = ctx.Sessions.Where(s => sessionStrs.Contains(s.ID) && s.IP.Equals(ip));
if (ret.Any())
return ret.Select(s => s.User).ToList();
else
return null; // or new List<User>();
Google led me here, so I'll throw my experience out there for anyone having a similar issue.
My project was using EF fluent configuration to query an existing database. I couldn't figure out why I was receiving any data back despite being able to query the table with other tools.
After banging my head against the wall, I finally discovered that I'd mislabeled the column type like so:
Property(x => x.DateCreated)
.HasColumnName("datetiem") // strings are the devil
Make sure you're using FirstOrDefault instead of First if you're extracting something from a list.

Categories