0

私はEntity FrameworkとMVCを学んでいます。

これは私のモデルです:

    public class ChatLogContext : DbContext
{
    public ChatLogContext()
        : base("connString")
    {
    }

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

[Table("ChatLogs")]
public class ChatLogs
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int ChatLogId { get; set; }
    [Column("Message")]
    public string Message { get; set; }
    [Column("UserId")]
    public int UserId { get; set; }

}

そして、これは私のコントローラーコードです:

        public ActionResult Index()
    {

        using(var db = new ChatLogContext())
        {
            var list = db.ChatLogs.Select(p => p.Message).SingleOrDefault();
            ViewBag.data = list;
            return View();

        }


    }

次に、次のようにビューでそのデータにアクセスします。

@model Chat.Models.ChatLogs
@Html.Raw(ViewBag.data)

これでここに見られるように、1つのレコードにアクセスできます。

しかし、Entity Frameworkを使用してChatLogsテーブルからすべてのレコードにアクセスし、Razorメソッド(foreach)でビューに渡す方法を学びたいので、そのデータをフォーマットできます(VSが生成するデフォルトのテーブルは好きではありません)。私は現在、1 行 1 列に ViewBag を使用しています。これが最も遠いところです。

私の頭脳に役立つ例をGoogleで見つけることができません。

助けていただければ幸いです。

PS: 純粋なエンティティで作業するか、linq(エンティティへの linq) を混在させる方が良いですか?

4

1 に答える 1

0

Typically the Index action is for showing a grid of all the entities (in this case ChatLogs).

One of the points of the Razor View Engine is that you get typed Views. So typically I would pass the data to the view directly as opposed to using the ViewBag.

public ActionResult Index()
{

    using(var db = new ChatLogContext())
    {
        var list = db.ChatLogs.ToList();
        return View(list);

    }
}

The next step is to have the View typed to IEnumerable<ChatLog>. Visual Studio should help you with that. Then you can just foreach over the ChatLogs.

于 2013-08-05T03:11:28.147 に答える