nginx unicorn_使用实体框架4进行简单代码优先-Magic Unicorn Feature CTP 4

nginx unicorn

nginx unicorn

Microsoft's been releasing a number of right-sized LEGO pieces lately. In case you missed it, Betas have been announced for:

微软最近发布了许多合适尺寸的乐高积木。 万一您错过了它,我们将宣布Beta版:

  • SQL 4 Compact Edition - It has a small embedded file-based SQL Database, and a web-server called IIS Express that's compatible with the full version of IIS.

    SQL 4精简版-它有一个小型的嵌入式基于文件SQL数据库,并呼吁IIS Express中的Web服务器这是与IIS的完整版本兼容。

  • "Razor" Page Syntax - A way to make pages/ViewEngine called "Razor." Your sites can be later be expanded to use all of ASP.NET MVC. It's a simple syntax that is easy to learn.

    “剃刀”页面语法 -一种称为“剃刀”的制作页面/ ViewEngine的方法。 您的站点以后可以扩展为使用所有ASP.NET MVC。 这是一种简单易懂的语法。

  • WebMatrix - It's a small (15 megs if you have .NET 4, 50megs if you don't) lightweight IDE for making ASP.NET or PHP websites. Good for non-pro developers.

    WebMatrix中-这是一个很小(15兆,如果你,如果你不具备.NET 4,50megs)作出ASP.NET或PHP网站轻量级IDE。 适合非专业开发人员。

    • It uses the WebDeploy engine to deploy apps to hosts, setting up permissions, copying databases, etc.

      它使用WebDeploy引擎将应用程序部署到主机,设置权限,复制数据库等。
    • WebMatrix also has the free Search Engine Optimization Toolkit built in, so you can spider your own site and see how Search Engines see it. It'll make recommendations and store reports.

      WebMatrix还具有免费的搜索引擎优化工具包 内置,因此您可以搜索自己的网站并查看搜索引擎如何看待它。 它将提出建议并存储报告。

    WebMatrix - It's a small (15 megs if you have .NET 4, 50megs if you don't) lightweight IDE for making ASP.NET or PHP websites. Good for non-pro developers.

    WebMatrix中-这是一个很小(15兆,如果你,如果你不具备.NET 4,50megs)作出ASP.NET或PHP网站轻量级IDE。 适合非专业开发人员。

  • IIS Express - A version of the IIS 7.5 Web Server that can be run as non-admin, isn't installed as a service, that will also integrate with Visual Studio

    IIS Express -可以以非管理员身份运行的IIS 7.5 Web服务器版本,未作为服务安装,也将与Visual Studio集成

More details to come on all this. Howver, on the tooling side, I did get a chance to talk to Damian Edwards, a developer working on some of this stuff and I put video up on Channel 9 yesterday.

关于这一切的更多细节。 但是,在工具方面,我确实有机会与从事此类工作的开发人员Damian Edwards进行了交谈,我昨天在第9频道上放了视频

There's lots of cool pieces that are packaged up with WebMatrix initially, but these pieces are interesting for pro developers as well.

最初,WebMatrix打包了很多很酷的工具,但是对于专业开发人员来说,这些工具也很有趣。

Still, something's missing.

不过,仍然缺少某些东西。

In my mind, it's been too hard to talk to databases. I like LINQ to SQL and used it on the first NerdDinner version, but since EF4 sucks so much less is way better than earlier versions of EF, Jon and I updated NerdDinner to use EF. It was easy, but I would have liked to code first, and code only if I could.

在我看来,与数据库对话太难了。 我喜欢LINQ to SQL,并在第一个NerdDinner版本上使用了它,但是由于EF4的 吸取 量比早期版本的EF好得多,因此Jon和我更新了NerdDinner以使用EF。 这很容易,但是我希望先进行编码,并且仅在可能的情况下进行编码。

Microsoft announced a new Entity Framework CTP today. It has the romantic and wonderful name "Microsoft ADO.NET Entity Framework Feature CTP4" which is lame. You can say "EF Feature CTP4" but I like "EF Magic Unicorn Edition" but that's just me. We're getting the tech better at Microsoft but still can't get naming right. Whadayagonnado? Still, it makes EF a pleasure.

Microsoft今天宣布了一个新的Entity Framework CTP 。 它有一个浪漫而美妙的名字“ Microsoft ADO.NET实体框架功能CTP4 ”。 您可以说“ EF Feature CTP4”,但我喜欢“ EF Magic Unicorn Edition”,但仅此而已。 我们正在使Microsoft的技术变得更好,但仍然无法正确命名。 Whadayagonnado? 尽管如此,它仍然使EF成为一种乐趣。

It's got a lot of interesting features and choices, and while it's still a CTP, you should take a minute and check it out. 

它具有许多有趣的功能和选择,尽管它仍然是CTP,但您应该花一点时间进行检查。

To get a more detailed version of this walkthrough plus downloadable sample code, check out the ADO team's excellent blog post.

获得本演练的更详细版本以及可下载的示例代码请查看ADO团队的出色博客文章

通过代码优先模型进行快速CRUD (Quick CRUD via a Code First Model)

After you install it (it won't mess up your system if you do), go and create a new whatever project. For my little example, I'll make a new ASP.NET MVC Website. It works for me better than a console app to illustrate a point.

安装后(如果安装,它不会弄乱您的系统),请去创建一个新的项目。 对于我的小例子,我将创建一个新的ASP.NET MVC网站。 它比控制台应用程序更能说明我的观点。

Add a reference to Microsoft.Data.Entity.CTP.dll.

添加对Microsoft.Data.Entity.CTP.dll的引用。

Make a new class, maybe in the Models folder, and name it something like Book. Add some code like this. Notice it's just code. Nothing derives from anything.

在“模型”文件夹中创建一个新类,并命名为Book。 添加一些这样的代码。 注意这只是代码。 一无所有。

public class Book
{
[Key]
public int ISBN { get; set; }
[Required]
public string Title { get; set; }
public DateTime FirstPublished { get; set; }
public bool IsFiction { get; set; }
}

Notice I've put [Key] and [Required] on this class, but if that bothers me, I could put these kinds of declarations in a more fluent way in my database context class, in OnModelCreating.

注意,我已经在该类上添加了[Key]和[Required],但是如果让我感到困扰,则可以在OnModelCreating中的数据库上下文类中以更加流畅的方式放置这些类型的声明。

builder.Entity<Book>().HasKey(b => b.ISBN);
builder.Entity<Book>().Property(b => b.Title).IsRequired();

To access my data, Here's a SimpleBookCatalog...

要访问我的数据,这是一个SimpleBookCatalog ...

public class SimpleBookCatalog : DbContext
{
public DbSet<Book> Books { get; set; }
}

Next, I'll make a new Controller, via right|click Add Controller. I'll make a BookController.

接下来,我将通过右键|单击添加控制器来创建一个新的控制器。 我将创建一个BookController。

public class BookController : Controller
{
SimpleBookCatalog db = new SimpleBookCatalog();

public ActionResult Index()
{
var books = db.Books;
return View(books);
}
...
}

I'll right click on the Index method and make an Index view. Then I'll run my app.

我将右键单击Index方法并创建一个Index视图。 然后,我将运行我的应用程序。

image

No data. What if I look in my SQL Management Studio? I got a Database created for me with a convention-based name since I didn't supply one.

没有数据。 如果我查看我SQL Management Studio,该怎么办? 因为没有提供数据库,所以为我创建了一个基于约定的名称的数据库。

If I specified a different connection string, that DB could be anywhere.

如果我指定了不同的连接字符串,则该数据库可以在任何地方。

However, if use a different database provider, like say, a SQL 4 Compact Edition one, setting it as the default in my Application_Start:

但是,如果使用其他数据库提供程序(例如SQL 4 Compact Edition) ,则将其设置为我的Application_Start中的默认数据库:

Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");

Then when I run my app and look in my App_Data folder:

然后,当我运行我的应用程序并查看我的App_Data文件夹时:

SQL Compact Edition Database file in App_Data

So I got a file based database without doing anything and I don't need SQL Server. (Yes, I can change the name, location, etc.) If I do nothing, I get a reasonable convention.

因此,我不做任何事情就获得了基于文件的数据库,并且不需要SQL Server。 (是的,我可以更改名称,位置等。)如果不执行任何操作,则会得到合理的约定。

Next, I'll add two Create methods, one for a GET and one for a POST. In Create, I'll add my new book and save the changes:

接下来,我将添加两个Create方法,一个用于GET,一个用于POST。 在“创建”中,我将添加新书并保存更改:

public ActionResult Create()
{
return View();
}

[HttpPost]
public ActionResult Create(Book book)
{
db.Books.Add(book);
db.SaveChanges();
return RedirectToAction("Index");
}

I'll right click, Add View, and make a Create View. Run my app, look at the empty list, then click Create.

我将右键单击“添加视图”,然后创建一个“创建视图”。 运行我的应用程序,查看空白列表,然后单击创建。

My Create Form

Click Create, and I'm redirected back to the Index page:

单击创建,然后将我重定向回索引页面:

Book List

Back on the Index page, I can change the link to Details to use our primary key:

返回“索引”页面,我可以将“详细信息”的链接更改为使用我们的主键:

<%: Html.ActionLink("Details", "Details", new { id=item.ISBN })%> |

Create a Details View and add a Details method:

创建一个Details视图并添加一个Details方法:

public ActionResult Details(int id)
{
var book = db.Books.Find(id);
return View(book);
}

See that Find method? That's there automatically. I can certainly use al the LINQy goodness as well, but as you can see, CRUD is simple. I can hook up Edit and Delete in a few minutes as well.

看到该查找方法吗? 那是自动存在的。 我当然也可以使用LINQy的优点,但是如您所见,CRUD很简单。 我也可以在几分钟内连接“编辑”和“删除”。

Here's the whole thing:

这是整个事情:

public class BooksController : Controller
{
SimpleBookCatalog db = new SimpleBookCatalog();

public ActionResult Index()
{
var books = db.Books;
return View(books);
}

// GET: /Books/Details/5
public ActionResult Details(int id)
{
var book = db.Books.Find(id);
return View(book);
}

// GET: /Books/Create
public ActionResult Create()
{
return View();
}

[HttpPost]
public ActionResult Create(Book book)
{
db.Books.Add(book);
db.SaveChanges();
return RedirectToAction("Index");
}

// GET: /Books/Edit/5
public ActionResult Edit(int id)
{
return View(db.Books.Find(id));
}

// POST: /Books/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
var book = db.Books.Find(id);
UpdateModel(book);
db.SaveChanges();
return RedirectToAction("Index");
}

// GET: /Books/Delete/5
public ActionResult Delete(int id)
{
var book = db.Books.Find(id);
return View(book);
}

// POST: /Books/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
db.Books.Remove(db.Books.Find(id));
db.SaveChanges();
return RedirectToAction("Index");
}
}

So that's a nice simple controller that uses a model that was written in just code. The database and its schema was created for me. The DbContext is LINQable with stuff like Add, Find, and Remove all just there. Plus, it's all EF under the hood, so if you need more complex stuff, you can do it.

这是一个很好的简单控制器,它使用仅用代码编写的模型。 该数据库及其架构是为我创建的。 DbContext是LINQable的,其中包括“添加”,“查找”和“删除”之类的东西。 另外,所有这些都是底层的EF,因此,如果您需要更复杂的东西,可以做到这一点。

For example, here's a more complex Code First Model with Collections, and more attributes. I show some fluent wiring up of relationships later on, although there are conventions that can assign bi-directionality based on naming.

例如,这是带有集合和更多属性的更复杂的代码优先模型。 尽管有些约定可以基于命名分配双向性,但稍后我将展示一些流畅的关系连接。

public class Book
{
[Key]
public int ISBN { get; set; }
[Required]
public string Title { get; set; }
[Required]
public DateTime FirstPublished { get; set; }
[Required]
public bool IsFiction { get; set; }

public virtual Publisher Publisher { get; set; }
[RelatedTo(RelatedProperty="Author")]
public virtual Author Author { get; set; }
}

public class Person
{
[ScaffoldColumn(false)]
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}

public class Author : Person
{
[ScaffoldColumn(false)]
public int AuthorId { get; set; }

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

public class Publisher
{
[ScaffoldColumn(false)]
public int PublisherId { get; set; }
[Required]
[MaxLength(50)]
public string Name { get; set; }

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

public class SimpleBookCatalog : DbContext
{
public DbSet<Book> Books { get; set; }
public DbSet<Person> People { get; set; }
public DbSet<Author> Authors { get; set; }
public DbSet<Publisher> Publishers { get; set; }
}

Also, "Magic Unicorn EF" supports DataAnnotations (or validation via Fluent interfaces), so those [Required] and [StringLength] stuff from before? Those apply not only in JavaScript, but also at the Server-side and Database persistence layers.

另外,“ Magic Unicorn EF”还支持DataAnnotations(或通过Fluent接口进行验证),那么以前的那些[Required]和[StringLength]东西呢? 这些不仅适用于JavaScript,而且适用于服务器端数据库持久性层。

You can make your own strategies for creating databases, based on what's going on with the model, if it's changed, etc. Here's some built-in examples. Yours can do whatever you like. Here the SimpleBookCatalog is the DbContext from before.

您可以根据模型的运行情况,更改的情况等来制定自己的数据库创建策略。这是一些内置示例。 您可以做任何您喜欢的事。 这里的SimpleBookCatalog是以前的DbContext。

//This is the default strategy.  It creates the DB only if it doesn't exist
Database.SetInitializer(new CreateDatabaseOnlyIfNotExists<SimpleBookCatalog>());
//Recreates the DB if the model changes but doesn't insert seed data.
Database.SetInitializer(new RecreateDatabaseIfModelChanges<SimpleBookCatalog>());
//Strategy for always recreating the DB every time the app is run.
Database.SetInitializer(new AlwaysRecreateDatabase<SimpleBookCatalog>());

Connection Strings for the SQL 4 CE provider are simpler (like, they are possible to memorize, which is amazing, considering how hard they are now). For example:

SQL 4 CE提供程序的连接字符串更简单(例如,可以记住它们,考虑到现在的辛苦程度,这真是太棒了)。 例如:

<add name="SimpleBookCatalog" connectionString="Data Source=C:\FooFoo\MyBooks.sdf" providerName="System.Data.SqlServerCe.4.0"/>

Here's some examples of fluent mappings and setting up relationships to give you an idea of the kinds of things you can do, while avoiding looking at any visual designers. It all depends on how clean you need your POCO (Plain Old CLR Objects) to be.

以下是一些流畅的映射和建立关系的示例,可让您大致了解可以做的事情,同时避免看任何视觉设计师。 这完全取决于您需要的POCO (普通旧CLR对象)的清洁程度。

modelBuilder.Entity<Book>().HasKey(b => b.ISBN);
modelBuilder.Entity<Book>().HasRequired(b => b.Title);
modelBuilder.Entity<Book>().HasRequired(b => b.Author).WithMany(a => a.Books);
modelBuilder.Entity<Publisher>().Property(p => p.Name).MaxLength = 50;
modelBuilder.Entity<Author>().HasMany(a => a.Books).WithRequired();

These configurations can be batched up into a class that handles configuration for a specific entity so you can reuse them and more easily config like this.

可以将这些配置分批处理到一个类中,该类处理特定实体的配置,因此您可以重用它们,并且可以像这样更容易地进行配置。

builder.Configurations.Add(new BookConfiguration());

All this is a really basic example as a means of introduction and for my own learning, but so far I like it. It takes just a few minutes to get a lot done without much code. Since this is all Entity Framework, I can put an OData service on top of my model really quickly and then start consuming those services from iPhones or whatever.

所有这些都是一个非常基本的示例,可以作为介绍和进行我自己的学习的手段,但是到目前为止,我还是喜欢它。 无需太多代码,只需几分钟即可完成很多工作。 由于这都是实体框架,因此我可以很快地将OData服务置于模型之上,然后开始从iPhone或其他设备中使用这些服务。

It'll be interesting to take a sample like Nerd Dinner or MVC Music Store and change them to use Code First EF and the Razor View Engine and see if they are more readable and how many fewer lines of code they are.

拿一个像Nerd Dinner或MVC Music Store这样的样本并将其更改为使用Code First EF和Razor View Engine来查看它们是否更具可读性以及减少多少行代码,将很有趣。

Related Links

相关链接

翻译自: https://www.hanselman.com/blog/simple-code-first-with-entity-framework-4-magic-unicorn-feature-ctp-4

nginx unicorn

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值