Reputation: 1066
I am new to Linq to Entity (Infact I am new to Linq) and I am struggling to insert a row.
Following a number of tutorials (None of which seem to agree with each other or are very detailed) I managed to come up with the following code but I'm struggling to work out how to use what I have ...
The DB looks like this:
namespace IdeaGen.Data
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class IdeaGenEntities : DbContext
{
public IdeaGenEntities()
: base("name=IdeaGenEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<Idea> Ideas { get; set; }
public DbSet<User> Users { get; set; }
}
}
My model looks like this:
public class NewIdea
{
public int IdeaID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int UserID { get; set; }
}
(I haven't done the user model yet)
And my controller looks like this but isn't compiling.
using (IdeaGenEntities ctx = new IdeaGenEntities())
{
var ideas = ctx.Ideas;
NewIdea idea = new NewIdea();
idea.Description = model.Description;
idea.Title = model.Title;
ctx.Ideas.Add(idea);
ctx.SaveChanges();
}
Oh and I also use this as per one of the tutorials ...
namespace IdeaGen.Data
{
public class DBBase
{
private IdeaGenEntities _IdeaGenEntity = new IdeaGenEntities();
public IdeaGenEntities IdeaGenEntity {get {return _IdeaGenEntity; } }
}
}
Could anyone point me in the right direction? Once I get a foundation understanding of what I am doing I will be able to work the rest out but with nothing to work from I am kinda in the dark about where I have gone wrong.
Thanks in advance
Edit:
Got it thanks to user user619656. My updated Controller looks like this ...
IdeaGenEntities ctx = new IdeaGenEntities();
Idea Idea = new Idea();
Idea.Title = model.Title;
Idea.Description = model.Description;
ctx.Ideas.Add(Idea);
ctx.SaveChanges();
Thanks for your help
Upvotes: 3
Views: 7142
Reputation: 799
Ideas
is a DbSet<Idea>
and you can only add Idea
objects to this collection.
But here
NewIdea idea = new NewIdea();
idea.Description = model.Description;
idea.Title = model.Title;
ctx.Ideas.Add(idea);
you are adding a NewIdea object to Ideas, and that's where you get the error.
Upvotes: 4