Answer the question
In order to leave comments, you need to log in
How to avoid error regarding 1:0..1 in Entity Framework??
Hello, my task is that I pull the image path from the database and display it on the page, the image itself is stored in the file system. Here is my model 1:0..1
public class Album
{
public string Title { get; set; }
public virtual Genre Genre { get; set; }
public virtual ICollection<FileDetail> FileDetails { get; set; }
[Key]
public int AlbumId { get; set; }
[DisplayName("Genre")]
public int GenreId { get; set; }
[DisplayName("Artist")]
public int ArtistId { get; set; }
public decimal Price { get; set; }
[DisplayName("Album Art URL")]
[StringLength(1024)]
public string AlbumArtUrl { get; set; }
public virtual Artist Artist { get; set; }
public virtual MainFileDetails MainFileDetails { get; set; }
}
}
public class MainFileDetails
{
public Guid Id { get; set; }
public string FileName { get; set; }
public string Extension { get; set; }
[Key, ForeignKey("Album")]
public int AlbumId { get; set; }
public virtual Album Album { get; set; }
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "AlbumId,Title,GenreId,ArtistId,Price,AlbumArtUrl")] Album album)
{
if (ModelState.IsValid)
{
//New Files
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
MainFileDetails fileDetail = new MainFileDetails()
{
FileName = fileName,
Extension = Path.GetExtension(fileName),
Id = Guid.NewGuid(),
AlbumId = album.AlbumId
};
var path = Path.Combine(Server.MapPath("~/Upload/"), fileDetail.Id + fileDetail.Extension);
file.SaveAs(path);
db.Entry(fileDetail).State = EntityState.Modified;
}
}
db.Entry(album).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId", "Name", album.ArtistId);
ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name", album.GenreId);
ViewBag.AlbumId = new SelectList(db.MainFileDetails, "AlbumId", "FileName", album.AlbumId);
return View(album);
}
<img src="~/Upload/@(Model.MainFileDetails.Id + Model.MainFileDetails.Extension)" width="240" height="240" />
If you create a new product, then a new record with an ID will be linked to the MainFileDetails table and there will be no excepption. And what then to do with already existing data? I have to manually add data to the MainFileDetails table so that there are no exceptions, well, I have a couple of records, but what if there were a million? What to do in such a situation? Thanks
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question