asp.net ef 7 Einfügen, wenn IDENTITY_INSERT auf OFF festgelegt ist, Probleme

Wenn ich versuche zu speichern, zu meiner Datenbank bekomme ich die Fehlermeldung

SqlException: Nicht einfügen expliziter Wert für die Identitätsspalte in Tabelle "Photo", wenn IDENTITY_INSERT auf OFF festgelegt ist.

Ich bin mit asp.net 5 MVC 6 mit EF-7 auf Visual Studio 2015
Es gibt eine Menge ähnlicher Fragen. Die meisten Lösungen haben, die nicht unterstützt werden asp.net 5 MVC-6-oder EF 7(Einer sagte, verwenden Sie eine Daten-Annotation, die das problem beheben würde in EF-6). Die anderen haben nicht geklappt. Ich versuche, nicht zu Fragen, außer als letzten Ausweg.

Mein design ist, dass jeder Benutzer viele Ordner und einen Ordner mit vielen Fotos.

Fügte ich public ICollection<UserFolder> UserFolders { get; set; } zu ApplicationUser

Modell:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations.Schema;

namespace FamPhotos.Models
{
    public class UserFolder
    {
        public int ID { get; set; }
        public string Name { get; set; }

        public ICollection<Photo> Photo { get; set; }

        public string ApplicationUserId { get; set; }
        public virtual ApplicationUser ApplicationUser { get; set; }
    }

    public class Photo
    {
        public int ID { get; set; }
        public string Description { get; set; }
        public DateTime UploadDate { get; set; }
        public string Url { get; set; }

        public int UserFolderId { get; set; }
        public UserFolder UserFolder { get; set; }

    }
}

Die Controller-Methode

//POST: Photos/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(Photo photo, IFormFile files, int id)
    {
        if (files == null)
        {
            ModelState.AddModelError(string.Empty, "Please select a file to upload.");
        }
        else if (ModelState.IsValid)
        {
            photo.UploadDate = DateTime.Now;
            photo.UserFolderId = id;

            var folderName = _context.UserFolder.Where(q => q.ID == id).Single().Name; 

            //TODO:  Check for image types
            var fileName = photo.ID.ToString() + ContentDispositionHeaderValue.Parse(files.ContentDisposition).FileName.Trim('"');
            var filePath = Path.Combine(_applicationEnvironment.ApplicationBasePath, "Photos", User.GetUserName(), folderName, fileName);
            await files.SaveAsAsync(filePath);

            photo.UserFolder = _context.UserFolder.Where(q => q.ID == id).Single();
            photo.Url = "~/Photos/" + fileName;

            _context.Add(photo);
            _context.SaveChanges();


            return RedirectToAction("Index");
        }
        return View(photo);
    }

Ansicht:

    @model FamPhotos.Models.Photo

@{
    ViewData["Title"] = "Create";
}

<h2>Create</h2>

<form asp-action="Create" asp-controller="Photos" method="post" enctype="multipart/form-data">
    <div class="form-horizontal">
        <h4>Photo</h4>
        <hr />
        <div asp-validation-summary="ValidationSummary.ModelOnly" class="text-danger"></div>
        <input type="file" name="files" />
        <label asp-for="Description" class="col-md-2 control-label"></label>
        <div class="col-md-10">
            <input asp-for="Description" class="form-control" />
            <span asp-validation-for="Description" class="text-danger" />
        </div>
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</form>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
    <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
}

Meinem DbContext:

   namespace FamPhotos.Models
{
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        protected override void OnModelCreating(ModelBuilder builder)
        {
            builder.Entity<UserFolder>()
                .HasMany(q => q.Photo)
                .WithOne(c => c.UserFolder)
                .HasForeignKey(c => c.UserFolderId);



            base.OnModelCreating(builder);
            //Customize the ASP.NET Identity model and override the defaults if needed.
            //For example, you can rename the ASP.NET Identity table names and more.
            //Add your customizations after calling base.OnModelCreating(builder);
        }
        public DbSet<Photo> Photo { get; set; }
        public DbSet<ApplicationUser> ApplicationUser { get; set; }
        public DbSet<UserFolder> UserFolder { get; set; }
    }
}

Dank.

  • Sie sind verwirrt, indem Sie den Fehler. IDENTITY_INSERT OFF bedeutet, dass die Datenbank nicht zulässt, dass Sie die insert-und identity-Wert (dies ist der normale Zustand, wenn Sie eine identity-Spalte). Biegen Sie IDENTITY_INSERT AUF in Fällen, in denen Sie zum Beispiel die Wiederherstellung einer Reihe von Aufzeichnungen, die einschließen, Identität, Schlüssel, und Sie möchten, überschreiben Sie die Taste Wert in einer update-oder geben Sie es in einem insert. AUF bedeutet ERMÖGLICHEN, Sie legen eine Identität.
  • Ihre OnModelCreating ist unvollständig. Blick auf die akzeptierte Antwort auf diese Frage. stackoverflow.com/questions/15258571/...
InformationsquelleAutor Dave D | 2016-01-19
Schreibe einen Kommentar