---
# System prepended metadata

title: mod02
tags: [mvc]

---

```csharp
[httpstatus](https://www.webfx.com/web-development/glossary/http-status-codes/)
//=========================
//model
public class Opera
{
    public int OperaID { get; set; }
    public string Title { get; set; }
    public int Year { get; set; }
    public string Composer { get; set; }
}
//operacontroller.cs
public ActionResult Index()
{
    Opera opera = new Opera
    {
        OperaID = 1,
        Title = "尤利迪西",
        Year = 1600,
        Composer = "佩里"
    };

    return View(opera);
}
// opera/index.cshtml
@model Mod02.Models.Opera            
<ul>
    <li>@Model.OperaID</li>
    <li>@Model.Title</li>
    <li>@Model.Year</li>
    <li>@Model.Composer</li>
</ul>

//============================
C# Type
	Value	
		int	non-nullable
		int?	nullable
	Reference
		string	nullable

Expression<Func<Opera,TValue>>
--> Lambda Expression

m=>m.Title

//Model
public class Opera
{
    [DisplayName("編號")]
    public int OperaID { get; set; }

    [Required(ErrorMessage = "歌劇名稱不可以為空白")]
    [StringLength(200)]
    [DisplayName("歌劇名稱")]
    public string Title { get; set; }

    [DisplayName("年代")]
    public int Year { get; set; }

    [Required]
    [DisplayName("作者")]
    public string Composer { get; set; }
}
//View
<ul>
    <li>@Html.DisplayName("operaid"): @Html.Display("operaid")</li>
    <li>@Html.DisplayNameFor(m=>m.Title): @Html.DisplayFor(m=>m.Title) </li>
    <li>@Html.DisplayNameFor(m=>m.Year): @Html.DisplayFor(m=>m.Year) </li>
    <li>@Html.DisplayNameFor(m=>m.Composer): @Html.DisplayFor(m=>m.Composer) </li>
</ul>
//===================================
// CheckValidYear.cs
public class CheckValidYear:ValidationAttribute
{
    public CheckValidYear()
    {
        ErrorMessage = "The earliest opera is Daphne, 1598, by Corsi, Peri, and Rinuccini";

    }
    public override bool IsValid(object value)
    {
        if (value == null) return true;

        int year = (int) value;

        return year>1597;
    }
}
// Opera.cs
[DisplayName("年代")]
[CheckValidYear]
public int? Year { get; set; }

//===============================
// home/index.cshtml
@model Mod02.Models.Opera
<form action="~/Opera">
    @Html.EditorForModel()
    <input type="submit" />
</form>

// operacontroller.cs
public ActionResult Index(int operaid, string title)
{
    Opera opera = new Opera
    {
        OperaID = operaid,
        Title = title,
        Year = 1600,
        Composer = "佩里"
    };
    return View(opera);
}

public ActionResult Index(Opera opera) //Model Binding
{
    return View(opera);
}

public bool Index(Opera opera) //Model Validation
{
    return ModelState.IsValid;
}

public ActionResult Index(Opera opera) 
{
    if (ModelState.IsValid)
    {
        return View(opera);
    }
    else
    {
        return View("~/views/home/index.cshtml",opera);
    }            
}

//=======================
// operacontext.cs
public class OperaContext:DbContext
{
    public DbSet<Opera> Operas { get; set; }
}

// operacontroller.cs
public class OperaController : Controller
{
    OperaContext context=new OperaContext();
    public ActionResult Index()
    {
        return View(context.Operas.ToList());
    }
}

// opera/index.cshtml
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Opera List</title>
</head>
<body>
    <div>
       <h1>Opera List</h1>
    </div>
</body>
</html>
//=================================
// web.config
<connectionStrings>
	<add name="OperaContext" 
		 connectionString="server=(localdb)\mssqllocaldb;database=operadb;trusted_connection=true;"
		 providerName="System.Data.SqlClient"/>
</connectionStrings>

// OperasInitializer.cs
public class OperasInitializer : DropCreateDatabaseAlways<OperaContext>
{
    protected override void Seed(OperaContext context)
    {
        var operas = new List<Opera>
        {
            new Opera {
                Title = "Cosi Fan Tutte",
                Year = 1790,
                Composer = "Wolfgang Amadeus Mozart",
            },
            new Opera {
                Title = "Rigoletto",
                Year = 1851,
                Composer = "Giuseppe Verdi",
            },
            new Opera {
                Title = "Nixon in China",
                Year = 1987,
                Composer = "John Adams"
            },
            new Opera {
                Title = "Wozzeck",
                Year = 1922,
                Composer = "Alban Berg"
            }
        };

        operas.ForEach(o => context.Operas.Add(o));

        context.SaveChanges();
    }
}

//global.asax.cs
protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    Database.SetInitializer(new OperasInitializer());
}

//==================================
// opera/index.cshtml
             
@model IEnumerable<Mod02.Models.Opera>
             
<table border="1">
    <thead>
        <tr>
            <th>@Html.DisplayNameFor(m => m.Title)</th>
            <th>@Html.DisplayNameFor(m => m.Year)</th>
            <th>@Html.DisplayNameFor(m => m.Composer)</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>@Html.DisplayFor(m => item.Title)</td>
                <td>@Html.DisplayFor(m => item.Year)</td>
                <td>@Html.DisplayFor(m => item.Composer)</td>
            </tr>
        }
    </tbody>
</table>
//=================================
1. web.config
	修改connectionstring database=operadb2
2. 對OperasInitializer.cs點選[exclude from project]
3. global.asax.cs
	//Database.SetInitializer(new OperasInitializer());
4. build
//=======================================
Code First Migrations

tools->nuget package manager->package manager console

pm>enable-migrations –EnableAutomaticMigration:$true

//configruation class
protected override void Seed(Mod02.DAL.OperaContext context)
{
    //  This method will be called after migrating to the latest version.

    //  You can use the DbSet<T>.AddOrUpdate() helper extension method
    //  to avoid creating duplicate seed data.

    context.Operas.AddOrUpdate(o => o.Title, new Opera
    {
        Title = "Cosi Fan Tutte",
        Year = 1790,
        Composer = "Wolfgang Amadeus Mozart",
    },
        new Opera
        {
            Title = "Rigoletto",
            Year = 1851,
            Composer = "Giuseppe Verdi",
        },
        new Opera
        {
            Title = "Nixon in China",
            Year = 1987,
            Composer = "John Adams"
        },
        new Opera
        {
            Title = "Wozzeck",
            Year = 1922,
            Composer = "Alban Berg"
        });
}


pm>update-database -verbose

```