Entity framework relation mapping is not working - entity-framework

print("Hello World !");
I'm a beginner into the .NET world, i'm trying to use entity framework but i have a problem, my relations entities are not loaded, i followed the microsoft documentation but.
Here are my models :
[Table("Path")]
public class Path
{
[Key]
public int PathId { get; set; }
[Required]
public string Title { get; set; }
public List<Image> Images { get; set; }
[Required]
public string Description { get; set; }
[Required]
public float LocationX { get; set; }
[Required]
public float LocationY { get; set; }
[Required]
public string QrCode { get; set; }
public List<Mark> Marks { get; set; }
}
[Table("Mark")]
public class Mark
{
[Key]
public int MarkId { get; set; }
public int Value { get; set; }
public int PathForeignKey { get; set; }
[ForeignKey("PathForeignKey")]
public Path Path { get; set; }
}
[Table("Image")]
public class Image
{
[Key]
public int ImageId { get; set; }
[Required]
public string Name { get; set; }
public string Description { get; set; }
public int PathForeignKey { get; set; }
[ForeignKey("PathForeignKey")]
public Path Path { get; set; }
[Required]
public string Source { get; set; }
}
For me, everything is ok, i even have the correct entries into my database :
database entries
But my relation dont load when i'm reading database into my controller.
[HttpGet]
public IEnumerable<Path> GetAll()
{
return _context.Paths.ToList();
}
results
I'm sorry, i guess it is probably a stupid beginner error but i dont see what i did wrong. I tried with various database system, with virtual or not ...

Mark your navigation properties as virtual. For example:
[Table("Mark")]
public class Mark
{
[Key]
public int MarkId { get; set; }
public int Value { get; set; }
public int PathForeignKey { get; set; }
[ForeignKey("PathForeignKey")]
public virtual Path Path { get; set; } //Added virtual keyword
}
and a second way to load navigation properties is to use Include while fetching data:
return _context.Marks.Include(x => x.Path).ToList();

Related

How to post some collection of <T> data to MVC action?

public class Graphic
{
...
...
[ScaffoldColumn(false)]
public int GraphicId { get; set; }
public virtual ICollection<GraphicArtwork> GraphicArtworks { get; set; }
}
public class GraphicArtwork
{
[Key]
public int GraphicArtworkId { get; set; }
public int GraphisId { get; set; }
[Required(ErrorMessage = "The {0} is required.")]
[StringLength(500)]
public string ArtOptionText { get; set; }
public decimal Price { get; set; }
[DisplayName("Active")]
public bool IsActive { get; set; }
public DateTime CreatedDate { get; set; }
[NotMapped]
public int TotalRecordCount { get; set; }
}
I have this two table and model. Here I have one Graphics with Many Art Work option. I have created my Artwork Option in view using Knockout.js. now my problem is that How to post(Action method) these data so that I can insert into GraphicArtwork table.
[HttpPost]
public ActionResult Add(Graphic data)
{
// "data" will contain all posted values
}

Entity Framework Code first adds unwanted foreign key column

I have a many to one relationship between Categories and News.
The problem I'm having is that EF keeps adding a foreign key colum to my table which I dont want!
News class
public class News
{
public News()
{
}
[Key]
public int NewsID { get; set; }
public int PublishedByID { get; set; }
public string PublishedByFullName { get; set; }
public string PublishedByEmail { get; set; }
public DateTime DatePublished { get; set; }
public string Title { get; set; }
public string PreviewText { get; set; }
public string BlobName { get; set; }
public virtual Category Category { get; set; }
}
Categories class
public class Category
{
public Category()
{
News = new HashSet<News>();
}
[Key]
public int CategoryID { get; set; }
public string Name { get; set; }
public string CategoryTypeName { get; set; }
public virtual ICollection<News> News { get; set; }
}
Database
My question
How do I remove Category_CategoryID in News table?
I'm guessing i'm missing some code in my OnModelCreating method.
You need to add id field in News class to reference Category.
public class News
{
[Key]
public int NewsID { get; set; }
public int CategoryID { get; set; } // added
public int PublishedByID { get; set; }
public string PublishedByFullName { get; set; }
public string PublishedByEmail { get; set; }
public DateTime DatePublished { get; set; }
public string Title { get; set; }
public string PreviewText { get; set; }
public string BlobName { get; set; }
public virtual Category Category { get; set; }
}

Code First one to many relationship and category with parent category

public class Category
{
[Key]
public int CategoryId { get; set; }
public int ParentCategoryId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int Status { get; set; }
public virtual ICollection<Category> ParentCategories { get; set; }
public virtual ICollection<ImageSet> ImageSets { get; set; }
[ForeignKey("ParentCategoryId")]
public virtual Category ParentCategory { get; set; }
}
public class ImageSet
{
[Key]
public int ImageSetId { get; set; }
public int CategoryId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string InsertDate { get; set; }
public int Status { get; set; }
public virtual ICollection<Image> Images { get; set; }
[ForeignKey("CategoryId")]
public virtual Category Category { get; set; }
}
public class Image
{
[Key]
public int ImageId { get; set; }
public int ImageSetId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string ImageUrl { get; set; }
public string ThumbImageUrl { get; set; }
public string InsertDate { get; set; }
public int Status { get; set; }
[ForeignKey("ImageSetId")]
public virtual ImageSet ImageSet { get; set; }
}
Context:
public DbSet<Category> Categories { get; set; }
public DbSet<Image> Images { get; set; }
public DbSet<ImageSet> ImageSets { get; set; }
error page:Introducing FOREIGN KEY constraint 'FK_dbo.ImageSets_dbo.Categories_CategoryId' on table 'ImageSets' may
cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or
ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could
not create constraint. See previous errors.
Whats the problem?
You need to add this:
modelBuilder.Entity<ImageSet>()
.HasRequired(is => is.Category)
.WithMany(c => c.ImageSets)
.WillCascadeOnDelete(false);
Here are good explanations of why this is happening :
https://stackoverflow.com/a/19390016/1845408
https://stackoverflow.com/a/17127512/1845408

MVC 4 code first database initializer doesn't work

I had to stop at the same stages following different MVC 4 code first technique tutorials, because database initialization failed.
Using the connection
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-DbTestApp-20130205173443;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-DbTestApp-20130205173443.mdf" providerName="System.Data.SqlClient" />
I can't even create or manage the database, which I want to be generated from my models
public class Category
{
public int Id { get; set; }
[Required]
[MinLength(4)]
[MaxLength(64)]
public string Name { get; set; }
public virtual IEnumerable<Article> Articles { get; set; }
}
public class Article
{
public int Id { get; set; }
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
[Required]
[MinLength(4)]
[MaxLength(64)]
public string Title { get; set; }
[Required]
[MinLength(16)]
[MaxLength(1024)]
[DataType(DataType.MultilineText)]
public string Content { get; set; }
[Required]
[Display(Name = "Post Anonymous?")]
public bool IsAnonymous { get; set; }
public int AuthorId { get; set; }
public virtual Author Author { get; set; }
public virtual IEnumerable<Comment> Comments { get; set; }
}
public class Author
{
public int Id { get; set; }
[MinLength(3)]
[MaxLength(64)]
public string AuthorName { get; set; }
public virtual IEnumerable<Article> Articles { get; set; }
public virtual IEnumerable<Category> Categories { get; set; }
}
public class Comment
{
public int Id { get; set; }
public int ArticleId { get; set; }
public virtual Article Article { get; set; }
[Required]
[MinLength(3)]
[MaxLength(64)]
public string Author { get; set; }
[MaxLength(64)]
public string Title { get; set; }
[Required]
[MinLength(4)]
[MaxLength(512)]
public string Content { get; set; }
}
using the context below
public class BlogContext : DbContext
{
public DbSet<Category> Categories { get; set; }
public DbSet<Article> Articles { get; set; }
public DbSet<Author> Authors { get; set; }
public DbSet<Comment> Comments { get; set; }
public BlogContext()
: base("DefaultConnection")
{
Configuration.ProxyCreationEnabled = false;
}
}
I also set the initializer in Global.asax Application_Start() method:
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<BlogContext>());
The problem comes when I'm trying to call
var articles = db.Articles.Include(a => a.Category).Include(a => a.Author);
inside my BlogController's Index() method to return a view with the list of stored articles. That happens every time calling a DB related methods, the error message is:
Model compatibility cannot be checked because the database does not contain model metadata. Model compatibility can only be checked for databases created using Code First or Code First Migrations.
In the tutorials I found nothing about problems like that and the solutions I read couldn't solve the problem.
Any ideas?
Thanks
DropCreateDatabaseIfModelChanges requires there to be a previous model already in place before it will compare the two. To start up the database you'll need to use the DropCreateDatabaseAlways initializer.

Eager Load Entity Framework Navigation Property error

I'm trying to eager load some child entities like so:
_context.Sites.Where(x => x.ID == siteID).Include(s => s.SiteLoggers).FirstOrDefault();
However, the error I am getting is:
A specified Include path is not valid. The EntityType 'MyProject.Dal.EF.Site' does not declare a navigation property with the name 'SiteLoggers'.
What is saying is correct, as MyProject.Dal.EF.Site does not exist, the object exists in MyProject.Domain.Entities.Site
What am I missing??? Thanks!
POCOs:
namespace MyProject.Domain.Entities
{
public class Site
{
public int ID { get; set; }
public int LocationID { get; set; }
public bool Active { get; set; }
public bool Deleted { get; set; }
public string Name { get; set; }
public virtual Location Location { get; set; }
public virtual IEnumerable<SiteLogger> SiteLoggers { get; set; }
}
}
namespace MyProject.Domain.Entities
{
public class SiteLogger
{
public int ID { get; set; }
public int UID { get; set; }
public int SiteID { get; set; }
public string Name { get; set; }
public int LocationID { get; set; }
public bool Active { get; set; }
public bool Deleted { get; set; }
public virtual Site Site { get; set; }
public virtual Location Location { get; set; }
}
}
You need to use ICollection instead of IEnumerable, because EF requires that your navigation properties are defined as ICollection<T>.
public virtual ICollection <SiteLogger> SiteLoggers { get; set; }