3

In SQL Server 2008 I have a view like this:

CREATE VIEW products AS
   SELECT a.ID, a.Name, b.ID as SubID, b.Name as SubName
   FROM main_product as a 
   INNER JOIN sub_product as b on a.ID = b.mainID

This is my model:

Public class Products
{
    public int ID { get; set; }
    public int Name { get; set; }
    public int SubID { get; set; }
    public int SubName { get; set; }
}

Now how can I map my MVC3's view to the SQL Server view?

UPDATE

I tried with this:

 public class PartialContext : DbContext
 {       
     protected override void OnModelCreating(DbModelBuilder modelBuilder)
     {
         modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
     }

     public DbSet<Test> Test { get; set; }

     public DbSet<Products> Products { get; set; }
 }

and Controller:

public class ViewController : Controller
{
    private PartialContext db = new PartialContext();

    //
    // GET: /View/

    public ViewResult Index()
    {
        return View(db.Products.ToList());
    }
}

This effort gave me an error: "Invalid object name 'dbo.Products'."

EDIT 2

Just to clarify. I want to use both code first and database first technique. It means I want to create both database and model class manually, not through code generator or database generator

UPDATE

Problem solve. I make a mistake on naming model class

6
  • 1
    Regular entity, use it like a regular Table, exactly the same Commented May 20, 2013 at 7:09
  • How are you accessing your data? Raw ADO.NET? Entity Framework? Something else? Commented May 20, 2013 at 7:14
  • I'm using Entity Framework Commented May 20, 2013 at 7:17
  • AFAIK you cant insert data in the sql VIEW so there is not point in mapping the mvc view on to the db view Commented May 20, 2013 at 7:36
  • I want to map mvc view with db view for front end read only purpose Commented May 20, 2013 at 7:38

1 Answer 1

5

update the EF model

enter image description here

now simply you can query the view like

 using (var ctx = new YourDBContext())
  {
    var result = from t in ctx.product
                 select new Products{
                   ID= ctx.ID,
                   Name=ctx.Name
                 };    
  }

more information on the following link

http://www.mssqltips.com/sqlservertip/1990/how-to-use-sql-server-views-with-the-entity-framework/

I think it will help you.

Sign up to request clarification or add additional context in comments.

1 Comment

That really helpful, but I'm looking for the way to use code first and db first at a same time. I mean that I want to create the model class manually, not through the code generator

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.