asp.net ef 7将IDENTITY_INSERT设置为OFF时的插入问题

Dav*_*e D 3 c# asp.net-mvc entity-framework visual-studio-2015

当我尝试保存到数据库时,出现错误

SqlException:当IDENTITY_INSERT设置为OFF时,无法为表“照片”中的标识列插入显式值。

我在Visual Studio 2015上使用带有EF 7的asp.net 5 MVC 6有很多类似的问题。大多数解决方案都不受asp.net 5 MVC 6或EF 7支持(据说使用的数据注释可解决EF 6中的问题)。其他人没有工作。我尽量不要问,除非万不得已。

我的设计是每个用户将有许多文件夹,并且一个文件夹将有许多照片。

我添加public ICollection<UserFolder> UserFolders { get; set; }到ApplicationUser

该模型:

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; }

    }
}
Run Code Online (Sandbox Code Playgroud)

控制器方法

// 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);
    }
Run Code Online (Sandbox Code Playgroud)

风景:

    @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>
}
Run Code Online (Sandbox Code Playgroud)

我的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; }
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢。

Eri*_*sch 7

如果您不希望ID由数据库生成,则应在模型上使用DatabaseGenerated属性,如下所示:

public class MyModel
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int ID {get;set;}
    ...
}
Run Code Online (Sandbox Code Playgroud)

实际上,EF7支持此属性。

请参阅https://docs.microsoft.com/zh-cn/ef/core/modeling/generated-properties


Jos*_*ury 6

如果要将主键插入数据库,则数据库列上没有标识。

该错误消息表明您正在尝试选择一个主键,并且数据库希望为您选择一个主键。

关闭身份或允许数据库选择主键。