ADO.NET EF what is the purpose of using List<> in the entities - code-first

Right now I'm learning ADO.NET Entity Framework and there's one thing that I can't explain to myself. Here is a source code from a tutorial I've been using recently:
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public User UserId { get; set; }
public virtual List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public virtual Blog Blog { get; set; }
}
public class User
{
public int UserId { get; set; }
public string Username { get; set; }
public string DisplayName { get; set; }
}
First I thought that the using of List<> is the way to implement Foreign Key-like behaviour but now knowing that's not the case why we need and for what purpose we use List<> in our entites?

To show that Blog have a lot of Posts, when you will build your project in DB will be the relation 1xBlog--->NxPost where N=unlimited. This will show that each Blog can have unlimited amount of Posts

Related

Map many to many objects using Entity Framework

For example we have profile and organisation. Both have articles.
public class Article
{
public int Id { get; set; }
public string Title { get; set; }
}
public class Profile
{
public int Id { get; set; }
public string Email { get; set; }
public virtual ICollection<Article> Articles { get; set; }
}
public class Organisation
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Article> Articles { get; set; }
}
In this way Article should have two kinds of parent so it should have something like parent type to be able to access a parent when you select articles directly.
public class Article
{
public int Id { get; set; }
public string Title { get; set; }
public int ParentId { get; set; }
public ArticleParentType Parent { get; set; }
}
Is it possible to map it using Entity Framework?
Is it a good idea to do it?
What is the best practice for storing this kind of data?
public class Article
{
public int Id { get; set; }
public string Title { get; set; }
public int ParentId { get; set; }
public ArticleParentType Parent { get; set; }
}
Is it possible to map it using Entity Framework?
Is it a good idea to do it?
Possible yes but not a good idea. The underlying Database can't use a foreign key for Parentid. It would be slow.
What is the best practice for storing this kind of data?
A simple approach, with 2 Nullable parents and without CascadeOnDelete:
public class Article
{
public int Id { get; set; }
public string Title { get; set; }
public virtual Profile Profile { get; set; }
public virtual Organisation Organisation { get; set; }
}
Alternatively you could use inheritance for Article, ie class OrganisationArticle : Article {}

Storing IEnumerable<string> in Entity Framework

Is it possible to store an IEnumerable<string> in Entity Framework?
I'm using code-first in ASP.NET MVC5 and I have a model that looks a little like this, but ImageUris does not appear as a column in my database (all the other properties do).
public class Product
{
[Key]
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Condition { get; set; }
public decimal Price { get; set; }
public IEnumerable<string> ImageUris { get; set; }
}
PS: In case you are interested in why I'm storing Uris rather than images themselves, they are uris to Azure Storage Blobs.
You cannot save multiple records in single column of the relational database. There is no such data type that supports this.
You can create a separate table for Image Uris and then store your image Uris there.
Your entity code would look something like this:
public class Product
{
[Key]
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Condition { get; set; }
public decimal Price { get; set; }
public virtual ICollection<ImageUri> ImageUris { get; set; }
}
public class ImageUri
{
[Key]
public int Id { get; set; }
public string Uri { get; set; }
}

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.

Data model for User Notifications of many Types

I am trying to figure out how to model notifications. This is what I tried.
public class NotificationType
{
public int NotificationTypeID { get; set; }
public string Type { get; set; }
public string Action { get; set; }
}
public class Notification
{
public int NotificationID { get; set; }
public bool ReadStatus { get; set; }
public DateTime DateCreated { get; set; }
[ForeignKey("User")]
public int UserID { get; set; }
[ForeignKey("NotificationType")]
public int NotificationTypeID { get; set; }
public int CommentID { get; set; }
public int ProjectID { get; set; }
public Comment Comment { get; set; }
public Project Project { get; set; }
public NotificationType NotificationType { get; set; }
public User User { get; set; }
}
Frankly, I feel like I have no idea what I am doing still, but let me tell you what I was trying to do, if it's a bad idea, tell me, if not please tell me how I do it.
I have Notifications that are for actions that occur related to a Comment, Reply and Project - That's why I have all those navigation properties and fields. I want to basically use the NotificationType to determine what it is and then use the appropriate ID field to get the information to display the notification to a user.
First problem, I can't seem to make those ID (CommentID ProjectID ) fields Nullable so I don't always have to have them.
How to I make them nullable using data annotations and or the fluent api OR design my model better?
Make them nullable properties
public class Notification
{
public int NotificationID { get; set; }
public bool ReadStatus { get; set; }
public DateTime DateCreated { get; set; }
[ForeignKey("User")]
public int UserID { get; set; }
[ForeignKey("NotificationType")]
public int NotificationTypeID { get; set; }
public int? CommentID { get; set; }
public int? ProjectID { get; set; }
public Comment Comment { get; set; }
public Project Project { get; set; }
public NotificationType NotificationType { get; set; }
public User User { get; set; }
}
Then use the fluent API
modelBuilder.Entity<Notification>().HasOptional(n => n.Comment).WithMany()
.HasForeignKey(n => n.CommentID);
I found this a kind of complex but complete notification system : http://library.blackboard.com/ref/df5b20ed-ce8d-4428-a595-a0091b23dda3/Content/Mini_TOCs/mt_admin_app_system_manage_comm_notify_frame.htm
I think that many good ideas can be borrowed from it.

Linking MVC4 Models By ID

Woke up yesterday wondering what all the fuss with MVC was about. So I found out and wow it's nice and stuff like that.
I'm used to using one related Linq to Sql DataContext DB in ASP.NET projects.
//Some ASP.NET Page Codebehind
DataContext dbEntire = new DataContext()
With MVC4 with the Entity framework you make the model and it creates a DB for you.
//Models/Article/Article.cs
public class ArticleDBContext: DbContext
{
public DbSet<Article> Articles { get; set; }
}
public class Article
{
public int ID {get;set;}
public string Title{ get; set; }
public int AuthorID { get; set; }
public string Body { get; set; }
public int CategoryID { get; set; }
public DateTime Submitted{ get; set; }
public DateTime LastModified { get; set; }
}
Author and Category are seperate Models.
But how do you set up all the database relations.. One to many, etc. etc. ?
public class ArticleDBContext: DbContext
{
public DbSet<Article> Articles { get; set; }
public DbSet<Category> Categories { get; set; }
}
public class Article
{
public int ID {get;set;}
public string Title{ get; set; }
public int AuthorID { get; set; }
public string Body { get; set; }
public int CategoryID { get; set; }
public virtual Category Category { get; set; }
public DateTime Submitted{ get; set; }
public DateTime LastModified { get; set; }
}
public class Category
{
public int ID {get;set;}
public string Name{ get; set; }
public virtual ICollection<Article> Articles { get; set; }
}
Go through some tutorials on Entity Framework Code First.
EF Code First and MVC
EF getting started