简体   繁体   English

无法将值NULL插入“ BaslikId”列中

[英]Cannot insert the value NULL into column 'BaslikId'

I want to have a relationship on my tables. 我想在桌子上建立关系。 I take this error when I update db. 更新数据库时出现此错误。

Cannot insert the value NULL into column 'BaslikId', table 'BlogSitesi.dbo.Konular'; column does not allow nulls. UPDATE fails.
The statement has been terminated.

My Models : 我的模特:

public abstract class BaseModel
{
    public int id { get; set; }
}


public class Baslik:BaseModel
{
    public string Ad { get; set; }
    public int KonuAdet { get; set; }

    public virtual List<Konu> Konular { get; set;}
}


public class Konu:BaseModel
{
    public string KonuBaslik { get; set; } 
    public string Icerik { get; set; }
    public int BaslikId { get; set; }

    public virtual Baslik Baslik { get; set; }
}

I want to create a relation between Konu and Baslik (1-n Relation). 我想在KonuBaslik之间建立一个关系(1-n关系)。

How can I fix this? 我怎样才能解决这个问题?

It seems that you are looking for a 0-n relationship between Konu and Baslik: 似乎您正在寻找Konu和Baslik之间的0-n关系:

modelBuilder.Entity<Konu>()
        .HasOptional(s => s.Baslik)
        .WithMany(g => g.Konu)
        .HasForeignKey(s => s.BaslikId);

Also, you need to specify your fk as int? 另外,您需要将fk指定为int? to make it nullable like the following: 使它可以为空,如下所示:

public int? BaslikId { get; set; }

Hi I think that you have set column property in your database to "NOT NULL" which means that the database will not allow you to insert NULL values to this column. 嗨,我认为您已将数据库中的列属性设置为“ NOT NULL”,这意味着数据库将不允许您向该列插入NULL值。 It's basic practice that id column should be set to NOT NULL. 基本做法是将id列设置为NOT NULL。 Why you want to insert NULL to id column in first place? 为什么首先要在id列中插入NULL? This will make trouble when you will do joins. 当您加入时,这会带来麻烦。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM