简体   繁体   English

当IDENTITY_INSERT设置为OFF时,C#无法为表“出租”中的标识列插入显式值

[英]C# Cannot insert explicit value for identity column in table “Rentals” when IDENTITY_INSERT is set to OFF

I am currently learning ASP.NET MVC and I'm learning to get an object via its ID and inserting its reference to the database. 我目前正在学习ASP.NET MVC,并且正在学习通过其ID获取对象并将其引用插入数据库。 However, I am getting this error 但是,我收到此错误

Cannot insert explicit value for identity column in table "Rentals" when IDENTITY_INSERT is set to OFF 当IDENTITY_INSERT设置为OFF时,无法为表“出租”中的标识列插入显式值

I have read around and I noticed that some people say to set identity insert to off because the ID of the referenced table is auto incremented? 我已经阅读了很多,发现有人说要将身份插入设置为关闭,因为引用表的ID是自动递增的? However I have read that this method is not recommended because it apparently locks off the table or is only useful for single users? 但是,我读到不建议使用此方法,因为它显然会锁定表或仅对单个用户有用? May I know what is the correct way to do this? 我可以知道什么是正确的方法吗?

This is my controller code that is trying to add a new Rental 这是我的控制器代码,正在尝试添加新的租赁

[HttpPost]
public IHttpActionResult CreateNewRental(RentalDTO RentalDTO)
{
    if (RentalDTO.MovieIds.Count == 0)
    {
        return BadRequest();
    }
    var customer = _context.Customers.SingleOrDefault(c => c.Id == RentalDTO.CustomerId);
    if (customer == null)
    {
        return BadRequest("Customer ID is not valid");
    }
    var movies = _context.Movies.Where(m => RentalDTO.MovieIds.Contains(m.Id)).ToList();
    if (movies.Count != RentalDTO.MovieIds.Count)
    {
        return BadRequest();
    }
    foreach (var movie in movies)
    {
        if (movie.NumberAvailable < 1)
        {
             return BadRequest();
        }
        movie.NumberAvailable--;
        var rental = new Rentals
        {
            Customer = customer,
            Movie = movie,
            DateRented = DateTime.Now,
        };
        _context.Rentals.Add(rental);
    }
    _context.SaveChanges();
    return Ok();
}

This is my rentals model 这是我的租金模式

public class Rentals
{
    public byte Id { get; set; }
    [Required]
    public Customers Customer { get; set; }
    [Required]
    public Movies Movie { get; set; }
    public DateTime DateRented { get; set; }
    public DateTime? DateReturned { get; set; }
}

This is the migration I used to create the table 这是我用来创建表的迁移

CreateTable(
            "dbo.Rentals",
            c => new
                {
                    Id = c.Byte(nullable: false, identity: true),
                    DateRented = c.DateTime(nullable: false),
                    DateReturned = c.DateTime(),
                    Customer_Id = c.Int(nullable: false),
                    Movie_Id = c.Int(nullable: false),
                })
            .PrimaryKey(t => t.Id)
            .ForeignKey("dbo.Customers", t => t.Customer_Id, cascadeDelete: true)
            .ForeignKey("dbo.Movies", t => t.Movie_Id, cascadeDelete: true)
            .Index(t => t.Customer_Id)
            .Index(t => t.Movie_Id);

UPDATE: 更新:

I have debugged my code and realized that when I added a new Rental, 0 was set as the ID. 我调试了代码,意识到在添加新的Rental时,将ID设置为0。 How do I set that automatically? 如何自动设置?

One of the columns in your Rentals table is an identity column (guessing it's the ID column). 租赁表中的一列是标识列(猜测是ID列)。 You generally don't want to explicitly set the value of an identity column, so your SQL server doesn't allow you without turning an option (IDENTITY_INSERT) on. 通常,您不想显式设置标识列的值,因此您的SQL Server不允许不打开选项(IDENTITY_INSERT)。

To avoid this problem, whatever mechanism you are using to save changes needs to know that when inserting, you don't specify the identity column. 为避免此问题,无论您使用什么机制来保存更改,都需要知道在插入时无需指定标识列。 Instead, you specify the rest of the columns and let the database decide the value of the identity column. 相反,您可以指定其余的列,然后让数据库确定标识列的值。 Similarly when updating, you won't generally be modifying this column, so your update shouldn't attempt to change it. 同样,在更新时,通常不会修改此列,因此您的更新不应尝试对其进行更改。

If you provide more information about what framework you're using for your model saving, we may be able to provide more specific answers. 如果您提供有关用于模型保存的框架的更多信息,我们也许能够提供更具体的答案。

This all changes if you actually have a need to specify a particular value for an identity column (such as copying data from one database to another is one example I've personally done this). 如果您实际上需要为Identity列指定一个特定的值(例如,将数据从一个数据库复制到另一个数据库就是我亲自完成的一个示例),则所有这些都将更改。 In that case, you can use the statement set IDENTITY_INSERT ON to allow the insert, then turn it back off when you're done. 在这种情况下,可以使用语句set IDENTITY_INSERT ON允许插入,然后在完成后将其关闭。

We ran into this issue today, also on a byte-type identity column. 今天,我们也在字节类型的标识列上遇到了此问题。 It didn't happen on the tables with an int -type identity column, but in the case of the byte column, what we assumed to be default behaviour was not being followed. 在带有int -type identity列的表上并没有发生这种情况,但是在字节列的情况下,我们没有遵循默认行为。 Despite it being marked with HasKey under the entity configuration, our system was still attempting to insert a value into the identity column. 尽管在实体配置下用HasKey标记了它,但我们的系统仍在尝试将一个值插入到identity列中。

The solution that we found was the addition of a Property within the entity's configuration, marking it explicitly as having its value generated by the database: 我们找到的解决方案是在实体的配置中添加一个Property,将其明确标记为其值由数据库生成:

Property(c => c.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

(with using System.ComponentModel.DataAnnotations.Schema ) 使用System.ComponentModel.DataAnnotations.Schema

Once we set this property, the identity-insert bug was resolved. 设置此属性后,身份插入错误已解决。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实体框架:当IDENTITY_INSERT设置为OFF时,无法为表&#39;[table]&#39;中的标识列插入显式值 - Entity Framework: Cannot insert explicit value for identity column in table '[table]' when IDENTITY_INSERT is set to OFF SqlException:当 IDENTITY_INSERT 设置为 OFF 时,无法为表 [表名] 中的标识列插入显式值 - SqlException: Cannot insert explicit value for identity column in table [Table name] when IDENTITY_INSERT is set to OFF 出现错误:当IDENTITY_INSERT设置为OFF时,无法在表&#39;Table&#39;中为标识列插入显式值 - Getting Error: Cannot insert explicit value for identity column in table 'Table' when IDENTITY_INSERT is set to OFF 当IDENTITY_INSERT设置为OFF时,无法为表&#39;ActivityInstances中的标识列插入显式值 - Cannot insert explicit value for identity column in table 'ActivityInstances' when IDENTITY_INSERT is set to OFF SqlException:当IDENTITY_INSERT设置为OFF时,无法为表&#39;Recipe&#39;中的Identity列插入显式值 - SqlException: Cannot insert explicit value for identity column in table 'Recipe' when IDENTITY_INSERT is set to OFF 当IDENTITY_INSERT设置为OFF时,无法在表&#39;MyTableName&#39;中为标识列插入显式值 - Cannot insert explicit value for identity column in table 'MyTableName' when IDENTITY_INSERT is set to OFF SqlException:当IDENTITY_INSERT设置为OFF时,无法为表&#39;AspNetUsers&#39;中的Identity列插入显式值 - SqlException: Cannot insert explicit value for identity column in table 'AspNetUsers' when IDENTITY_INSERT is set to OFF 当IDENTITY_INSERT设置为OFF时,无法在表&#39;candidatedetails&#39;中为identity列插入显式值 - Cannot insert explicit value for identity column in table 'candidatedetails' when IDENTITY_INSERT is set to OFF IDENTITY_INSERT设置为OFF时,EF无法为表“ PATIENT DONOR”中的标识列插入显式值 - EF Cannot insert explicit value for identity column in table 'PATIENT DONOR' when IDENTITY_INSERT is set to OFF IDENTITY_INSERT设置为OFF时,1:1映射并且无法为表&#39;DivisionParticipant&#39;中的Identity列插入显式值 - 1:1 mapping and Cannot insert explicit value for identity column in table 'DivisionParticipant' when IDENTITY_INSERT is set to OFF
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM