Is this code correct to add a record with a relationship Id? If i enter the Id directly, i get the following error
Cannot implicitly convert type 'int' to '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
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
.
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. 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. 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.
modelBuilder.Entity<Post>().HasRequired(p => p.Blog)
.WithMany(b => b.Posts)
.HasForeignKey(p => p.FKBlogId);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.