Ant
Ant

Reputation: 462

How to perform CRUD operations for a Model with a list of complex types with Entity Framework Code First?

I'm attempting to perform CRUD operations on an entity that contains a list of a complex type. I've tried several approaches and performed various Google searches, but so far all I've found is problems.

I have the following ViewModels:

public class GameViewModel
{
    public long Id { get; set; }
    public string Name { get; set; }
    public string OfficialWebsiteUrl { get; set; }

    public ReleaseDateViewModel ReleaseDate { get; set; }
    public List<ReleaseDateViewModel> ReleaseDates { get; set; }
}
public class ReleaseDateViewModel
{
    public long Id { get; set; }
    public long PlatformId { get; set; }
    public string PlatformName { get; set; }
    public long GameId { get; set; }

    public IEnumerable<SelectListItem> Platforms { get; set; }

    public bool IsActive { get; set; } = true;
}

I also have the following Platform model:

public class Platform
{
    public virtual long Id { get; set; }
    public virtual string Name { get; set; }
}

I've followed the advice on this extremely helpful post: Generate create view for model which have List object property

I currently have the ability set up to Add a new Game, which also adds a list of new ReleaseDates to my database and I can view these. But I'm having trouble performing updates and deletions.

I need to be able to delete a single ReleaseDate, and delete and Update a Game. If a Game is deleted all relevant ReleaseDates should be deleted. - I have no idea how to implement this.

For brevity I've omitted some properties of the models above and I've not included any controller or view code. If you need any of that information to help answer the question or to help make this a more helpful post, then let me know and I'll add them in.

Upvotes: 0

Views: 1296

Answers (1)

tede24
tede24

Reputation: 2354

Cascade delete will do the trick for Game deletion as stated by Eugene.

  • For updating GameViewModel leaving u changed release dates: build you GameViewModel object with desired values and Id (leave release dates collection empty), attach to context and set state to Modified and save changes
  • For adding a new release date: same than first, and add only the new release date to the collection
  • For updating or deleting a release date: work directly updating or deleting release date entity as a normal one. I mean don't try to delete release dates by removing from the ReleaseDates collection of game, that won't work at all

Hope this helps

Upvotes: 1

Related Questions