Entity Framework 6 Code First Fail - entity-framework-6

I'm new in Entity Framework and I'm testing a simple application but it doesn't work.
Let me explain step by setp what I'm doing:
1- Create a Console App using VS 2013 Express
2- Include a reference to EF6 by Nuget
3- Create the Student Class:
namespace CSharp_CodeFirst
{
public class Student
{
public int Id { get; set; }
public string name { get; set; }
public string email { get; set; }
}
}
4- Create the context class
using System.Data.Entity;
namespace CSharp_CodeFirst
{
public class StudentDataContext : DbContext
{
public StudentDataContext() : base()
{
}
public DbSet<Student> Students;
}
}
5- Create the code in Program.cs
namespace CSharp_CodeFirst
{
class Program
{
static void Main(string[] args)
{
using (var ctx = new StudentDataContext())
{
Student stud = new Student() { name = "New Student", email="test#test.com" , Id=1 };
ctx.Students.Add(stud);
ctx.SaveChanges();
}
}
}
}
6- Build without errors
7- When I execute the project I get the error :
An unhandled exception of type 'System.NullReferenceException' occurred in CSharp_CodeFirst.exe
Object reference not set to an instance of an object.
The error occur in this line of code : ctx.Students.Add(stud);
I'm using the sample in this site : http://www.entityframeworktutorial.net/code-first/simple-code-first-example.aspx
I Feel Like I'm Forgetting Something, but What ???
Thanks

Related

Azure with Xamarin.Android "You must be logged in to use this application"

I am recently starting to learn mobile development for my Final Year Project, and I am doing an Android application using Xamarin.Android and Azure Mobile Services.
I have created a Test DB and created one entry there, trying to make my Android App to connect to the DB and retrieve this entry. I am doing this to get an idea how to establish a connection and retrieve data, and from there I will start modification properly.
That is how my Model class look like (note that JSON properties are named exactly like the columns names in my DB.
using Newtonsoft.Json;
namespace com.parkkl.intro.Models
{
class TestTable
{
public int Id { get; set; }
[JsonProperty(PropertyName = "UserName")]
public string UserName { get; set; }
[JsonProperty(PropertyName = "deleted")]
public bool Deleted { get; set; }
[JsonProperty(PropertyName = "version")]
public string Version { get; set; }
[JsonProperty(PropertyName = "createdAt")]
public string Creation { get; set; }
[JsonProperty(PropertyName = "updatedAt")]
public string Updated { get; set; }
}
}
And that is how my activity look like
using Android.App;
using Microsoft.WindowsAzure.MobileServices;
using Android.OS;
using com.parkkl.intro.Models;
using System.Collections.Generic;
using Android.Widget;
namespace com.parkkl.intro
{
[Activity(Label = "ParkKL", MainLauncher = false, Icon = "#drawable/icon")]
public class MainActivity : Activity
{
#region Variables
public static MobileServiceClient client = new MobileServiceClient
(#"http://parkkl.azurewebsites.net/");
private IMobileServiceTable<TestTable> test = null;
private List<TestTable> testItems;
#endregion
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
test = client.GetTable<TestTable>();
testItems = new List<TestTable>();
GetData();
}
public async void GetData()
{
var collection = await test.Where(user => user.Id == 1).ToCollectionAsync();
foreach (var item in collection)
{
testItems.Add(
new TestTable
{
Id = item.Id,
UserName = item.UserName,
Deleted = item.Deleted,
Version = item.Version,
Creation = item.Creation,
Updated = item.Updated,
});
}
var finalItem = collection[0];
TextView text = (TextView)FindViewById(Resource.Id.TextFromDB);
text.Append(finalItem.UserName);
}
}
}
Now the issue is, every time I try to deploy the app, it throws this exception
Microsoft.WindowsAzure.MobileServices.MobileServiceInvalidOperationException:
You must be logged in to use this application
In my App Service in Azure, I have disabled all authentications, still I get this error. I am wondering where the issue is coming from?! I will much appreciate your help.
EDIT: I guess I found the issue, which was the permissions given on the table itself. However, I am still finding out a way to authenticate my app properly
Check out the book http://aka.ms/zumobook for details on how to deal with authentication.

How to bind parameter when it has reference to itself?

Here is a problem.
We have a simple web api controller with one class in it
public class CheckApiController : ApiController
{
public class Test
{
public int Id { get; set; }
public string SomeString { get; set; }
/*public Test ComplexType
{
get
{
return new Test()
{
SomeString = "wtf"
};
}
}*/
}
public List<Test> Get()
{
return new List<Test>(){
new Test(){Id = 1,SomeString = "1st string"},
new Test(){Id=2,SomeString = "2nd string"}
};
}
public HttpResponseMessage Post(Test testclass)
{
//do something
var response = Request.CreateResponse(HttpStatusCode.Created);
return response;
}
}
When I check in fiddler Get and Post methods everything is OK. But when i uncomment the property ComplexType in Test and try again POST method will respond with huge 500 internal server error:
Insufficient stack to continue executing the program safely. This can happen from having too many functions on the call stack or function on the stack using too much stack space.
So its simple StackOverflow exception. So why this error happens with field that has no setter or how can i ignore it in binding?
Think about whats happening here. When you POST the object WebApi is building your Test class to build it it gets the ComplexType, which returns a new Test, which gets ComplexType, which returns a new Test and so on until you run out of stack.
Having any logic in you Model you send to/from your Api is generally not a great idea. Here is some info on DTOs, which explains why http://www.servicedesignpatterns.com/requestandresponsemanagement/datatransferobject
Id Recommend amending your Test class to look like:
public class Test
{
public int Id { get; set; }
public string SomeString { get; set; }
public Test ComplexType { get; set; }
}
And then assigning the 'SomeString' value afterwards.

How to use a custom class in Odata v4 instead of class from designer.cs

C# Web.Api Odata APplication
I’m implementing Odata V4 for the first time and would like to use my own custom class instead of the data class from the designer.
Here is what I did:
I created a Data project in Visual Studios and added my SQL Linq data table “Video”
I created the data context as follows:
public class VideoDataContext : DbContext
{
public VideoDataContext(): base("name=VideoData")
{
DbSet<VideoEf> Videos { get; set; }
}
And my custom class as follows:
[Serializable]
[DataContract]
public class VideoEf : Repository
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Isrc { get; set; }
}
And model builder:
public Microsoft.OData.Edm.IEdmModel GetEdmModel()
{
ODataModelBuilder builder = new ODataConventionModelBuilder();
EntityTypeConfiguration<VideoEf> titleType = builder.EntityType<VideoEf>();
builder.EntitySet<VideoEf>("Video");
return builder.GetEdmModel();
}
And in my video controller:
public class VideoController : ODataController
{
VideoDataContext db = new VideoDataContext ();
[EnableQuery(PageSize = 20, MaxExpansionDepth = 5)]
public IHttpActionResult Get()
{
return Ok(db.Videos.AsQueryable());
}
When I make the call to get the video entities I keep getting a ” 406 Not Acceptable” error message
How can I ensure that the data returned from the database is mapped to my custom model ?
Is my model builder correct?
what could be causing the above error?
You don't need to return IQueryable because you have EnableQuery attribute, just return DbSet.
You also don't need any wcf attribute and EntityTypeConfiguration<VideoEf> titleType = builder.EntityType<VideoEf>();
Then it should just work.
Hope it helps.
Edit
My mistake for IQueryable, I also use it.

MVC update model with Code-Migrations

I am making my project in MVC4, where i am using my Code first approach. i need to update my model
i have a following property which needs to be update , how can i achieve this
public class ContactForm
{
public char Phone { get; set; }
}
public class ConContext : DbContext
{
public DbSet<ContactForm> ContactForms { get; set; }
}
}
i want to update Phone propery to
public char Phone { get; set; }
thnx in advance, i have installed migrations to my projet already
My configuration.cs
namespace MyCRM.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<MyCRM.Models.ConContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(MyCRM.Models.ConContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
}
}
}
The normal flow with EF code-first is too first update the model (a C# file) :
public class ContactForm
{
public string Phone { get; set; } //previously, this was let's say of type int
}
Then, you build your project and after that in the Package Manager Console, you have to call Add-Migration with some label (in order to rollback changes later if needed) :
Add-Migration Phone
This will add to your solution a file named like this 201409xxxxxxxx_Phone under the directory Migrations.
Then you have to put the changes to your database which can be done with the command (always in the console) :
Update-Database
Then, you should be done : the property Phone is of type string everywhere.

Null Reference Exception occurs when using odata in Web API calls

I have the following Product class:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
and the following Web API controller class:
public class ProductController : ApiController
{
public IQueryable<Product> Get()
{
var products = new List<Product>
{
new Product {Id = 1, Name = "Beans"},
new Product {Id = 2, Name = "Sausages"},
new Product {Id = 3, Name = "Bread"}
};
return products.AsQueryable();
}
}
I am using Fiddler to make requests to it. These work just fine:
localhost:49629/API/Product
localhost:49629/API/Product?$orderby=Name
But when I try to use filtering, such as:
localhost:49629/API/Product?$filter=Id gt 2
a null reference occurs. There is no source code available in the debugger, so I am unsure what has gone wrong. Can anyone help?
For Fiddler you need to encode the request:
localhost:49629/API/Product?$filter=Id%20gt%202

Resources