Code First con MVC Data Entity Framework

Web.config

  <connectionStrings>
    <add name="entity1" connectionString="Data Source=Xdesa;Initial Catalog=cv;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>


HomeController.cs

        public ActionResult Index()
        {
            Book libro;

            Author a = new Author();
            a.AuthorID = 1;
            a.FirstName = "nombre2";
            a.LastName = "apellido1";
            
            var book = new Book { BookID=1, Author=a, Title="titulo1" };
            using (var context = new MyContext())
            {
                context.Books.Add(book);
                context.SaveChanges();

                //List<Book> l = context.Books.Where(m => m.BookID > 1).ToList();
                libro = context.Books.Where(m => m.BookID > 1).FirstOrDefault();

            }
           
            return View(libro);
        }


MyContext.cs

    public class Book
    {
        [Key] 
        public int BookID { get; set; }
        public string Title { get; set; }

        public Author Author { get; set; }
    }

    public class Author
    {
        [Key] 
        public int AuthorID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public ICollection<Book> Books { get; set; }
    }

    public class MyContext : DbContext
    {
        public DbSet<Book> Books { get; set; }
        public DbSet<Author> Authors { get; set; }

        public MyContext()
            : base("name=entity1")
        {
        }
    }

Index.cshtml

<!DOCTYPE html>
@using Curriculums.Models
@model Book

@{
    ViewBag.Title = "Index";
}

@Model.BookID - @Model.Title

<h2>Index</h2>



No hay comentarios:

Publicar un comentario