John John - 3 months ago 10
Vb.net Question

How to use a class created by the entity framework

I have a project coming up so I decided to look at the entity framework. If I don't have to create a data manager I think this would be the way to go, if it works. I see lots of things about it but none of them are clear.

It created this class

namespace EFTest
{
using System;
using System.Collections.Generic;

public partial class SalesRepresentative
{
public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string CellPhone { get; set; }
}
}


How do I use it? Looking for examples I see things like this:

using (var ctx = new Context())
{
Employee emp = new Employee() { name = "Prashant" };
ctx.Employees.Add(emp);
ctx.SaveChanges();
}


I have a file called Model.Comntext with no context class in it. I tried changing it to dBContext but that doesn't work either.

I also found this:

CustomersComponent custc = new CustomersComponent();
Customers cust = custc.getCustomer(Id);
txtName.Text = cust.Name;
ddlCategories.SelectedValue = cust.Category.Id.ToString();


Well that has a Customer and a CustomerComponent. I have no such Component classes. I've spent half a day looking into this and am starting to wonder if the Entity Framework is a cousin of Microsoft Bob. Unless someone can tell me what I'm missing I will have to write my own data manager.

Answer

I resume step by step:

1 - Create a console project.

2 - Install EF using Nuget: Install-Package EntityFramework

3 - Create SalesRepresentative:

namespace EF {
    public partial class SalesRepresentative {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string CellPhone { get; set; }
    }
}

4 - Create GeneralContext

namespace EF {
    public class GeneralContext: DbContext {

        public DbSet<SalesRepresentative> SalesRepresentatives { get; set; }
    }
}

5 - So:

namespace EF {
    class Program {
        static void Main(string[] args) {

            using (var ctx = new GeneralContext()) {
                SalesRepresentative emp = new SalesRepresentative() { Name = "Prashant" };
                ctx.SalesRepresentatives.Add(emp);
                ctx.SaveChanges();
            }
        }
    }
}

Note: In the App.config file (or web.config) you should customize the connection string.