[英]C# Entity framework -- Add new record
Is this code correct to add a record with a relationship Id?添加具有关系 ID 的记录时,此代码是否正确? If i enter the Id directly, i get the following error
如果我直接输入Id,则会出现以下错误
Cannot implicitly convert type 'int' to 'Project.Models.Database.ArticleDatabase'无法将类型“int”隐式转换为“Project.Models.Database.ArticleDatabase”
Is this code below the correct way?这段代码低于正确的方法吗?
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();
//NOT WORKING
//不工作
// newArticle.Artdatabase = addarticle.ArticlegroupId
// newArticle.Artdatabase = addarticle.ArticlegroupId
That's because you're trying to set the ArticlegroupId
(which seems to be an int
) to a property that seems to be of type ArticleDatabase
.那是因为您试图将
ArticlegroupId
(似乎是一个int
)设置为一个似乎是ArticleDatabase
类型的ArticleDatabase
。
I assume your model looks something like this:我假设你的模型看起来像这样:
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; }
}
Alternative 1. Use the navigation property.备选方案 1. 使用导航属性。 When using the navigation property you need to attach it.
使用导航属性时,您需要附加它。
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();
Alternative 2. Use the foreign key-property.备选方案 2. 使用外键属性。 When using this option you need to explicitly define the foreign key in your model.
使用此选项时,您需要在模型中明确定义外键。
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();
Take a look at this article for defining foreign keys with fluent instead.看看这篇文章,用 fluent 来定义外键。
modelBuilder.Entity<Post>().HasRequired(p => p.Blog)
.WithMany(b => b.Posts)
.HasForeignKey(p => p.FKBlogId);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.