C#实体框架 - 添加新记录

时间:2016-09-09 11:43:03

标签: c# asp.net entity-framework

此代码是否正确添加具有关系ID的记录? 如果我直接输入Id,我会收到以下错误

无法将类型'int'隐式转换为'Project.Models.Database.ArticleDatabase'

此代码是否正确?

var newArticle = new Articles();

newArticle.Artname = addarticle.Articlename;

//NOT WORKING
// newArticle.Artdatabase = addarticle.ArticlegroupId

//WORKING, SEEMS WRONG
newArticle.Artdatabase = _context.ArticleDatabase.SingleOrDefault(c => c.Id == addarticle.ArticlegroupId);


newArticle.Articleaadddate = DateTime.Now;
newArticle.Articlelastedit = DateTime.Now;
newArticle.Artstatus = 3;

_context.Articles.Add(newArticle);
_context.SaveChanges();

1 个答案:

答案 0 :(得分:2)

  

//不工作

     

// newArticle.Artdatabase = addarticle.ArticlegroupId

这是因为您尝试将ArticlegroupId(似乎是int)设置为似乎属于ArticleDatabase类型的属性。

我认为你的模型看起来像这样:

public class Articles
{
    public string Artname { get; set; }

    [ForeignKey("ArtdatabaseId")]
    public virtual ArticleDataBase Artdatabase { get; set; }

    // For alternative 2 you'll need this.
    public int ArtdatabaseId { get; set; }
}

备选方案1.使用导航属性。使用导航属性时,需要附加它。

var newArticle = new Articles();

newArticle.Artname = addarticle.Articlename;

// Create the entity and attach it.
var artDataBase = new ArticleDataBase
{
    Id = addarticle.ArticlegroupId
};
_context.ArticleDatabase.Attach(artDataBase);

newArticle.Artdatabase = artDataBase;
newArticle.Articleaadddate = DateTime.Now;
newArticle.Articlelastedit = DateTime.Now;
newArticle.Artstatus = 3;

_context.Articles.Add(newArticle);
_context.SaveChanges();

备用2.使用外键属性。使用此选项时,需要在模型中显式定义外键。

var newArticle = new Articles();

newArticle.Artname = addarticle.Articlename;
// Note that I'm using ArtdatabaseId and not Artdatabase.
newArticle.ArtdatabaseId = addarticle.ArticlegroupId

newArticle.Articleaadddate = DateTime.Now;
newArticle.Articlelastedit = DateTime.Now;
newArticle.Artstatus = 3;

_context.Articles.Add(newArticle);
_context.SaveChanges();

看一下this article,用fluent定义外键。

modelBuilder.Entity<Post>().HasRequired(p => p.Blog) 
                .WithMany(b => b.Posts) 
                .HasForeignKey(p => p.FKBlogId);