无法将值NULL插入到EF Code First列中

时间:2016-05-22 01:21:21

标签: c# entity-framework ef-code-first

我有一个使用Entity Framework Code First的项目,我在插入错误“无法将值NULL插入列”中运行。 这是我的代码

[Table("Foo")]
public class Foo
{
    [Key]
    public int FooId { get; set; }
    public string Name { get; set; }

    public virtual List<Bar> Bar { get; set; }
}

[Table("Bar")]
public class Bar
{
    [Key, Column(Order = 0), ForeignKey("Foo")]
    public int FooId{ get; set; }

    [Key, Column(Order = 1), DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int BarId { get; set; }
    public DateTime Date { get; set; }

    public virtual Foo Foo { get; set; }
}

使用AutoMapper将Dto映射到Foo实体的插入方法。

    public bool Insert(Foo obj)
    {
        Foo newFoo = this.MapFooEntity(obj);
        this._context.Foo.Add(newFoo);
        this._context.SaveChanges();
        return true;
    }

Foo对象AutoMapper生成没有任何问题,它生成FooId = 0的Foo和任何BarId = 0的子(Bar)。 在我看来,EF应该看到BarId = 0并将下一个indentity ID附加到它,但我收到了这个错误。你有什么想法?

1 个答案:

答案 0 :(得分:1)

请尝试对您的代码进行以下修改:

在课程import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.ArrayAdapter; import android.widget.ListView; public class MainActivity extends Activity { public final static String EXTRA_MESSAGE = "MESSAGE"; private ListView obj; DataBaseHelper mydb; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mydb = new DataBaseHelper(this); ArrayAdapter<?> arrayAdapter = new ArrayAdapter<Object>(this, android.R.layout.simple_list_item_1); obj = (ListView) findViewById(R.id.listView1); obj.setAdapter(arrayAdapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } 中,将Bar放在

之前
[ForeignKey("FooId")]

并将public virtual Foo Foo { get; set; } 放在

之前
[InverseProperty("Foo")]
课程public virtual List<Bar> Bar { get; set; } 中的