This is my first experience with lists in general and I have kinda complex scenario. I want to add an object of type Story that has a list of Sentences that can be added dynamically. Sentence has a one-to-one relationship with Image and another one-to-one relationship with Audio (that are optional to add). I managed to add the sentences list to the database along with the story object. But I have no idea where to start with the other two entities.
Here are the models for each entity:
public class Story
{
public int StoryId { get; set; }
public string Title { get; set; }
public string Type { get; set; }
public DateTime Date { get; set; }
public virtual IEnumerable<Sentence> Sentences { get; set; } // one to many Story-Sentence
}
Sentence class:
public class Sentence
{
public int Id { get; set; }
public string SentenceText { get; set; }
public virtual Audio Audio { get; set; } // one to one Sentence-Audio
public virtual Image Image { get; set; } // one to one Sentence-Image
}
Image class:
public class Image
{
[Key]
[ForeignKey("Sentence")]
public int Id { get; set; }
public string ImageSelected { get; set; }
public virtual Sentence Sentence { get; set; }
}
And the Audio class is exactly like the Image class. The view.
@model Story
<div id="editorRows">
@foreach (var item in Model.Sentences)
{
<partial name="_SentenceEditor" model="item" />
}
</div>
<a id="addItem" asp-action="BlankSentence" asp-controller="StoryTest">Add Sentence...</a> <br />
<input type="submit" value="Finished" />
The partial view
@model Sentence
<div class="editorRow">
@using (Html.BeginCollectionItem("sentences"))
{
<span>Name: </span> @Html.EditorFor(m => m.SentenceText);
}
@using (Html.BeginCollectionItem("sentences"))
{
<span>Image: </span> @Html.EditorFor(m => m.Image.ImageSelected);
}
<a href="#" class="deleteRow">delete</a>
</div>
and I have some javascript that add and remove rows dynamically.
Finally in the Controller I'm just saving the model in the database
[HttpPost]
public async Task<IActionResult> AddTwo(Story model/*IEnumerable<Sentence> sentence*/)
{
if (ModelState.IsValid)
{
_db.Story.Add(model);
await _db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(model);
}
In short, I want to add an Image and Audio along with the sentence. And also be able to access the entire row correctly for editing.