I'm using code-first in Web Forms (not MVC) with EF4 and CTP5, and when trying to decorate a property with the [Key] attribute, it doesn't show up in the intellisense and get compilation error saying KeyAttribute was not found. Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace ERP.Models
{
public class CustomerAddress
{
[Key]
public int AddressID { get; set; }
public int CustomerID { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public int CityID { get; set; }
public int SateID { get; set; }
}
}
I have included the DataAnnotations library, all looks ok, but the [Key] attribute is not found. Any hint is highly appreciated. Thanks!
I didn't post it as answer first because I wasn't sure if the problem is not elsewhere. You must add System.ComponentModel.DataAnnotations.dll to project references.
Related
I’m creating a web API in MVC. The database is (thus far) simple, only three tables. I am unable to join them, though. I’ve tried three different methods for joining tables in the controller, and all return the same error, which is:
Cannot covert type (something*) to
‘Systems.Collections.Generic.IEnumerables< SalesDbApi.Sample>’ An
explicate conversion exists. Are you missing a cast?
(* The "something" portion is different depending on how the join occurs but the rest of the message remains the same, so I am assuming it is the relevant part.)
I’m guessing there is something wrong with how I have setup my Entity Relationships in Linq, because if I don’t do a join and just do a select all from Sample I get the following JSON back:
{"SampleId":10,"Barcode":"863760","CreatedAt":"2016-01-25T00:00:00","CreatedBy":10,"StatusID":3,"User":null,"Status":null}
User and Status aren’t fields in the Sample table. They are the names of the tables I am trying to link with, so I wouldn't expect them to appear.
Any idea on what I've done wrong?
Here are my three models:
Users.cs
namespace SalesDbApi
{
using System;
using System.Collections.Generic;
public partial class User
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public User()
{
this.Samples = new HashSet<Sample>();
}
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Sample> Samples { get; set; }
}
}
Statuses.cs
namespace SalesDbApi
{
using System;
using System.Collections.Generic;
public partial class Status
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Status()
{
this.Samples = new HashSet<Sample>();
}
public int StatusId { get; set; }
public string Status1 { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Sample> Samples { get; set; }
}
}
Samples.cs
namespace SalesDbApi
{
using System;
using System.Collections.Generic;
public partial class Sample
{
public int SampleId { get; set; }
public string Barcode { get; set; }
public Nullable<System.DateTime> CreatedAt { get; set; }
public int CreatedBy { get; set; }
public int StatusID { get; set; }
public virtual User User { get; set; }
public virtual Status Status { get; set; }
}
}
Here’s the code from the controller
SalesUsersController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using SalesDbApi;
namespace SalesProject.Controllers
{
public class SalesUsersController : ApiController
{
webapitestdbEntities1 db = new webapitestdbEntities1();
public IEnumerable<Sample> Get()
{
{
db.Configuration.ProxyCreationEnabled = false;
var query = from x in db.Samples
join q in db.Users
on x.CreatedBy equals q.UserId
select q.FirstName;
return query.ToList();
}
}
i think table Samples or table users not a data in database. besause linq can't accommodate table with no data.
I'm getting the following error:
Error 1 The type or namespace name 'keyAttribute' could not be found
(are you missing a using directive or an assembly reference?)
enter code here
c:\users\hp\documents\visual studio
2013\Projects\ProductApps\ProductApps\Models\Product.cs 13 10 ProductApps
My code:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace ProductApps.Models
{
public class Product
{
[key]
public int Id { get; set; }
public string ProductName { get; set; }
public string Price { get; set; }
public string Description { get; set; }
}
}
Is anyone able to suggest why I'm getting the error and how to fix it?
Please add
using System.ComponentModel.DataAnnotations;
to your using statements and try like (With capital K)
[Key]
public int Id { get; set; }
Do you have the System.ComponentModel.Annotations.dll assembly referenced in your project?
I have the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace MyTestWebsite.Models
{
public class Page
{
public int Id { get; set; }
public int AuthorUserId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Content { get; set; }
public bool Hidden { get; set; }
}
public class PageState
{
public int Id { get; set; }
public string Type { get; set; }
}
public class MyTestWebsiteDBContext : DbContext
{
public DbSet<Page> Pages { get; set; }
public DbSet<PageState> PageStates { get; set; }
}
}
I went to create a controller for Page and I found the model structure.. no problems.
This is, I need another model called PageState and my model list does not show this second model.
Is it usual to have a heck load of models.... regardless of them being linked in some way?
Do I just add a model on its own called PageState?
Is it usual to have a heck load of models
Yes, they are called view models. Each view should have a specific view model. It's perfectly normal to have many view models if you have many views. A view model could aggregate one or more of your EF domain models.
I am practicing Entity Framework. I am practicing Asp.net MVC framework using Razor Engine and EF Code First. In practicing it, I found to have few problems. The problem is the Entity Framework doesnt creates a database in my SQL.
I am using VisualStudio 2011 Beta Version with MSSQL 2008. I dont know what the problem is.
Help required. Below is my Code :
Person.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
namespace MvcDemo.Data
{
public class Person
{
[Key]
public int PersonID { get; set; }
[Required]
[StringLength(40)]
public string FirstName { get; set; }
[Required]
[StringLength(30)]
public int LastName { get; set; }
public int? Age { get; set; }
[ForeignKey("PrefixID")]
public Prefix Prefix { get; set; }
[Required]
public int PrefixID { get; set; }
}
}
Prefix.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
namespace MvcDemo.Data
{
public class Prefix
{
public int PrefixID { get; set; }
[Required]
[StringLength(20)]
public string PrefixName { get; set; }
}
}
MvcContext.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using MvcDemo.Data;
namespace MvcDemo.DataAccess
{
public class MvcContext : DbContext
{
public MvcContext()
: base("name = MvcDemoApp")
{
}
public DbSet<Person> People { get; set; }
public DbSet<MvcDemo.Data.Prefix> Prefix { get; set; }
}
}
ConnectionString:
<connectionStrings>
<add name="MvcDemoApp"
connectionString="Server=.;Initial Catalog=MvcDemoApp;Integrated Security=true"
providerName="System.Data.SqlClient" />
If this is all of your code it is not surprising that a database is not created. There is no code that executes commands against the database. As soon as you start iterating over e.g. MvcContext.People or do some insert you will notice that the database gets created.
There are plenty step-by-step examples online. I would pick one of them and do a walk through; you can try this one for example: http://msdn.microsoft.com/en-us/data/gg685467.aspx. It should cover most of the basics to get you started.
If you prefer video over text, search Channel 9, or pluralsight
You should operate package manager console to do it.
Ope package manager console window and run "update-database" command, there still a bug in this command so you need to specify "startupprojectname" param to execute it and connection string in you DbContext file.
When I try to add a 'MOVIES" controller, it errors: "There was an error generating 'MvcMovieSF.Models.MovieDBContext. Try rebuilding your project."
I have rebuilt the project and it continues to error. Thanks in advance!
namespace MvcMovieSF.Models
{
public class Movie
{
public int ID { get; set; }
public string Title { get; set; }
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
public decimal Price { get; set; }
}
public class MovieDBContext : DbContext
{
public DbSet Movies { get; set; }
}
}
JUST NOTICED: I'm not sitting at my own computer and I noticed SQLExpress services were not started; I don't have permission on this computer to start the service. Could that be the reason?
Adding a controller also modifies your context class. If you have implemented partial class to add some business rules into your context, the framework cannot successfully edit your partial class to find the correct points for its own insertions.
Stupid, though, removing the business rules might help. After creating your controller, you can put them back.
(at least, this worked for me, 10 minutes ago...)
Edit:
The Context class might be partially implemented like this:
public partial class MyDatabaseEntities : DbContext
{
public override int SaveChanges() { ... }
#region Some Business Rules Here
...
#endregion
}
Here, if you try to add a new controller, you will fail with the error: "There was an error generating 'MyDatabaseEntities'. Try rebuilding your project."
And rebuilding will not help at all...
My solution is:
Remove these business rules like this, of course, keep them in a safe place, as you will probably need them afterwards:
public partial class MyDatabaseEntities : DbContext
{
public override int SaveChanges() { ... }
}
Create your controller. You should be successful this time.
Remove the codes that are added by the framework from your context class:
public partial class MyDatabaseEntities : DbContext
{
public override int SaveChanges() { ... }
public DbSet<MyModelClass> MyModelClass { get; set; } // remove this line
}
Put the business rules back.
Hope this helps.
I had the same problem while adding new controller in ASP.NET MVC 4, I solved the problem by moving the Database.SetInitializer(new SomeDataContextInitializer()); from the constructor of the DBContext to Application_Start method in Global.asax.cs. Hope it helps.
#Bolt Thunder put me on the right track. In my case, the DbContext class was modified to have IDbSet for testing, which made it happen. Changed that - problem solved.
my project name was MVC and i had this class
public class download
{
public int download_id { get; set; }
public int download_category_id { get; set; }
public string download_name { get; set; }
public int download_size { get; set; }
public string download_description { get; set; }
public string download_path { get; set; }
public download_category download_category { get; set; }
}
public class download_category
{
public int download_category_id { get; set; }
public string download_category_name { get; set; }
}
public class DownloadDbContext : DbContext
{
public DbSet<download> downloads { get; set; }
public DbSet<download_category> download_categorys { get; set; }
}
and i got similar error when scaffolding(there was an error generating try rebuilding your project).
i am using visual studio 2012 version 11.0.50727.1 RTMREL and reference to entity as ...\EntityFramework.5.0.0\lib\net45\EntityFramework.dll
first i divide class into three classes (three seperate *.cs files) and also use DataAnnotations in download and download_category classes to use [key] for id columns and problem solved.
my classes were as below in Models folder :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MVC.Models;
using System.ComponentModel.DataAnnotations;
namespace MVC.Models
{
public class Download
{
[Key]
public int download_id { get; set; }
public int download_category_id { get; set; }
public string download_name { get; set; }
public int download_size { get; set; }
public string download_description { get; set; }
public string download_path { get; set; }
public Download_category download_category { get; set; }
}
}
and
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace MVC.Models
{
public class Download_category
{
[Key]
public int download_category_id { get; set; }
public string download_category_name { get; set; }
}
}
and
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace MVC.Models
{
public class DownloadDbContext:DbContext
{
public DbSet<Download> downloads { get; set; }
public DbSet<Download_category> download_categorys { get; set; }
}
}
I had the same problem as Susan. In my case specifying the model type for the DbSet (public DbSet<Movie> Movies ) in the context class fixed the problem.
I am using VS 2012 and i added the Entity Framework 5.0 package to the solution.