I have problem adding entity framework model to my project. Here is what I am doing:
1- Right click on project
2- Select add
3- In dialog select data from installed templates.
4- in installed template I cannot see ADO.NET entity framework template.
What should I install?
I use NuGet to install Entity framework 4.2.0.0 but no success.
I am using Visual Studio 2010
EDIT: Look for in the comment of answer for information.
Which method of Entity Framework are you trying to use? The most straightforward (in my opinion) is CodeFirst.
DataBaseFirst or ModelFirst
If you are using the wizard to create a model,
Right-click the project > Add New Item
In whichever language you are using, there should be a Data node. Under that node, select ADO.NET Entity Data Model.
Use the designer or wizard to model your ORM mapping
CodeFirst
(you can do this with an existing database, so the name is a bit of a misnomer)
Right-click the project > Add Class
Name it for one of your planned business objects (if using an existing database, classes can be mapped by name if they match tables in the database exactly)
Outline properties (if using an existing database, properties can be mapped by name if they match fields in the database exactly)
Right-Click on the project > Add Library Package Reference
Under Online>All search for Entity, and install the Entity Framework package (if already installed, it may just need to be referenced.
You may need to resolve using statements (or include if using VB.NET) in your entity class(es).
Example
using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
namespace Kiersted.Keps.BusinessObjects
{
[Table("Search", Schema = "mySchema")]
public class BatchSearch : KepsBusinessObject, IKepsBusinessObject
{
public BatchSearch() { }
public BatchSearch(DateTime created)
{
this.Created = created;
}
#region Data Properties
[Key]
[Column("BatchSearchID")]
public int SearchId{ get; set; }
[Column("uidQueueMaster")]
public Nullable<int> uidQueueMaster { get; set; }
[Column("DateCreated")]
public DateTime Created { get; set; }
[Column("DateCompleted")]
public Nullable<DateTime> Completed{ get; set; }
public string QueryTerms { get; set; }
[NotMapped]
public string LocalProperty { get; set; }
}
}
Note: If you are using an existing database, you can either name your classes the same as your tables or add the Table attribute to the class declaration. If you are putting your tables into a different schema (default is dbo) then you will need the Table tag regardless of the name so that you can specify the schema.
Note: If you are using and existing database, you can either name your properties the same as the corresponding fields or you can add the Column attribute.
Related
I have one project with EF and Code First approach and there using of Data Annotations was straight forward. Now I'm working with Database First and I see that using Data Annotations is more specific so I want to know the right steps to implement it.
The structure of my project that provides Data Access is this:
In ModelExtensions are all my files that I've created to add the Data Annotations to the DbContextModel.tt entities.
Here is the structure of one of my files in ModelExtensions:
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
namespace DataAccess.ModelExtensions
{
[MetadataType(typeof(MCS_ContentTypesMetaData))]
public partial class MCS_ContentTypes : BaseEntity
{
}
internal sealed class MCS_ContentTypesMetaData
{
[Required]
[StringLength(10)]
public string Name { get; set; }
}
}
I have several questions here. First - the namespace. Should it be like this namespace DataAccess.ModelExtensions or I have to remove the .ModelExtensions part. I was looking at a project using DB first and there the namespace was just DataAccess not sure why it is needed (if so). Also - Do I need to add some other references to the DbContextModel.tt entities? Now I use standard C# classes for this and then rename them to : public partial class MCS_ContentTypes : BaseEntity. Do I have to use a special approach for creating those to explicitly expose the connection between the entity and this file?
1) The namespace of your extension models must be the same as the namespace of EF auto-generated entity classes - If the namespace of DbContextModel.tt entity classes is DataAccess, you should set the namespace of your classes to DataAccess.
2) I doesn't get your question completely, however in this approach, names of entity classes and your classes must be the same.
The following example shows what it should be. Suppose that EF generates the following entity class for you:
namespace YourSolution
{
using System;
using System.Collections.Generic;
public partial class News
{
public int ID { get; set; }
public string Title { get; set; }
}
}
So, your partial classes should be like the following:
namespace YourSolution
{
[MetadataType(typeof(NewsAttribs))]
public partial class News
{
// leave it empty.
}
public class NewsAttribs
{
// Your attribs will come here.
[Display(Name = "News title")]
[Required(ErrorMessage = "Please enter the news title.")]
public string Title { get; set; }
// and other properties you want...
}
}
So, you doesn't need any : BaseEntity inheritance.
If you go to this website, http://www.asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/cs/intro-to-aspnet-mvc-3, you can see a tutorial where users create a movie database. I completed this tutorial with no problems, and attempted to create a new MVC application with some small changes that make the project more similar to what I want to do eventually.
Rather that create a model named Movie, I created one named Issue. Like movie, it has a few fields, but they are all different names and types. I went through the process exactly as is done in the tutorial, but whenever I try to add an issue to the database via the web UI, I get a DBEntityValidationException. I have not set any validation rules at this point in the process, so I am unsure of what the problem is.
Can someone give me some advice on fixing this so that I can add Issues to my database (as is done with movies on the online tutorial)?
Let me know if more information is needed; I am very new to this and may be lacking in details.
Here is the model code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace MvcApplication200.Models
{
public class Issue
{
public String id { get; set; }
public DateTime created { get; set; }
public DateTime closed { get; set; }
public String summary { get; set; }
public bool? importToTFS { get; set; }
}
public class IssueDBContext : DbContext
{
public DbSet<Issue> Issues { get; set; }
}
}
Update:I just redid the whole process, but rather than have different fields and different types, I made it so that my Issue model had the same number and same types of fields (with only different names). The error went away, so the problem must be with db format or something. I hope this makes the problem more clear.
I just ended up adding this class, which removes everything from the database when fields are changed. Then, I refresh the database, which is easy to do in my situation. One could add some items to the Seed method in order to ensure that some things remain in the updated database after it is cleared.
public class IssueInitializer : DropCreateDatabaseIfModelChanges<IssueDBContext>
{
protected override void Seed(IssueDBContext context)
{
//add things here
}
}
I am trying to dig into ASP.NET MVC 3, using the standard tutorials in the web, and I encounter a strage problem.
Currently, I am following the samples in a book, using a "Movie" class with movie genres stored in a separate entity, connected with a foreign key (okay, I am from Germany, so my class is named in German). I show only the relevant properties here. It's a database first approach using DbContext, my model was created from the edmx by using the EF 4.x DbContext Generator and the edmx was automatically created from the data base.
public partial class Film
{
public Film() { }
public int ID { get; set; }
public string Titel { get; set; }
public int GenreID { get; set; }
public virtual Genre Genre { get; set; }
}
public partial class Genre
{
public Genre() { }
public int GenreID { get; set; }
public string Name { get; set; }
}
When I create a new Controller with CRUD Views for the Film class, using a DBContext that provides a DBSet, I get an Edit view that uses a DropdownList to edit GenreID, labelled "Genre". Fine. That's what I want.
But then, I tried to create another edit view, separately. So I right-clicked into my Edit Action-Method, selected "Add View", called it "Edit2", used Film as model and "Edit" as scaffold template. In this view, I got a simple "EditorFor(m->m.GenreID)", labelled GenreID. That's not what I want.
Of course, I can change that manually. Of course, I can download a slew of scaffolding tools that claim to do better.
But I want to understand if this is a bug in the EF templates, or if my model is built wrong so that Genre / GenreID gets confused. When I create everything at once, scaffolding creates a DropDown, so there must be "just" some detail that's missing.
You will need to call your Action in your controller "Edit2".
I'm trying to make EntityFramework work with ASP .NET MVC3 using this tutorial:
http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application
Ok, I have my database, my .edmx model, model classes but one first thing I don't get is:
How does my DbContext derived class even know my .emdx model ? I don't fine where the "link" is created in this tutorial (maybe having several thing with the same name "SchoolContext", for the context as for the connexionstring is confusing ...)
When I run what I got for now with the code:
MMContext context = new MMContext();
List<EntityUser> testList = (from u in context.Users
select u).ToList();
I get:
System.Data.Edm.EdmEntityType: : EntityType 'EntityUser' has no key defined. Define the key for this EntityType.
System.Data.Edm.EdmEntitySet: EntityType: EntitySet �Users� is based on type �EntityUser� that has no keys defined.
Thank you for your help.
Assuming you are using the Code-First approach, you have to define a Key in your Users class:
public class User
{
public int Id { get; set; }
// ...
}
As mentioned from Kyle, if your ID field is not named "Id" you have to add the [Key] attribute:
using System.ComponentModel.DataAnnotations;
public class User
{
[Key]
public int u_Id { get; set; }
// ...
}
I used LINQ to SQL to generate a dbml file which contains the database model for my database table. I want to use UIHint to let MVC present some fields as DropDownLists or Checkboxes in edit mode. But if I change the file, it will be lost if it's been regenerated. How should I solve that issue? I'm quite new to MVC and still learning. I've set up a controller with views for all CRUD elements, but now I'm finetuning and I'm running into this problem.
Since Linq-to-SQL auto-generates partial classes, you'll need to create a partial 'buddy class' where you will add your Data Annotations. Your buddy class mirrors portions of the auto-generated class that you need to modify. You tie them together with [MetadataType(typeof(BuddyClassName))] The partial buddy class and the auto-generated partial class will be merged together when you compile your project.
In an example given that:
Your namespace is "Project.Models"
Your Linq-To-Sql class is called "Products"
using System.ComponentModel.DataAnnotations;
namespace Project.Models
{
[MetadataType(typeof(ProductsMeta))]
public partial class Products
{
// You can extend the products class here if desired.
public class ProductsMeta
{
// This is a Linq-to-Sql Buddy Class
// In here you can add DataAnnotations to the auto-generated partial class
[Key]
public int ProductKey { get; set; }
[Display (Name = "Product Name")]
[Required(ErrorMessage = "Product Name Required")]
[StringLength(255, ErrorMessage = "Must be under 255 characters")]
public string ProductName { get; set; }
[UIHint("MultilineText")]
public string Description { get; set; }
}
}
}
These articles were very helpful:
ScottGu: ASP.NET MVC 2: Model Validation
How to: Validate Model Data Using DataAnnotations Attributes
Validating with Data Annotation Validators
If you are going to use the entities directly you should create a partial class and add your annotations there. This way when the model is regenerated you will not lose your annotations.