实体框架4.1 - code先用现有的数据库,如何定义类,使用属性或EntityTypeConfiguration?有什么不同? [英] Entity Framework 4.1 - Code First with existing Database, how to define classes, using Attributes or EntityTypeConfiguration? What is the difference?

查看:133
本文介绍了实体框架4.1 - code先用现有的数据库,如何定义类,使用属性或EntityTypeConfiguration?有什么不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究EF很短的时间,并不能找到这个问题的答案。
我有现有的数据库,我使用codeFirst为模型创建类。

I have been studying the EF for a short time and cant find the answer to this question. I have existing database and I am using CodeFirst to create classes for the model.

有什么用区别的属性的和的 EntityTypeConfiguration 的定义表列的参数?

What is the difference in using Attributes and EntityTypeConfiguration to define parameters of table columns?

由于数据库已经定义了外键和唯一约束,等等,如何以及在何处实施为在ASP.NET MVC3使用最好的和最流畅的结果验证?

Since the database already has defined foreign keys and unique constraints, and so on, how and where to implement the validation for a best and most fluid result for use in ASP.NET MVC3?

是更好地实施的属性的和的 CustomValidation 的或使用的 TryCatch 的块来捕获从数据库错误?

Is it better to implement Attributes and CustomValidation or to use TryCatch blocks to catch errors from db?

确实的 Validator.TryValidateObject(myModelObject,环境,结果,真正的); 的定义只使用验证规则的属性的也可以使用的 EntityTypeConfiguration <定义的规则/ EM>?

Does Validator.TryValidateObject(myModelObject, context, results, true); use validation rules defined only as Attributes or can it use rules defined in EntityTypeConfiguration?

感谢您

推荐答案

请参阅有关如何从现有的数据库实体类的以下文章:

See the following article about how you can create your entity classes from existing database :

<一个href=\"http://blogs.msdn.com/b/adonet/archive/2011/03/15/ef-4-1-model-amp-database-first-walkthrough.aspx\" rel=\"nofollow\">http://blogs.msdn.com/b/adonet/archive/2011/03/15/ef-4-1-model-amp-database-first-walkthrough.aspx

code生成模板会为你的工作,你并不需要,如果你有一个现有的数据库来写他们。

Code generation templates will do the work for you, you don't need to write them if you have an existing db.

有关验证,您可以在同一空间下,创造新的部分类,并把DataAnottations你的属性。下面是一个例子:

For validation, you can create new partial classes under the same namespace and put DataAnottations for your properties. Here is an example for you :

using System.ComponentModel.DataAnnotations;
using System.ComponentModel;

namespace TugberkUgurlu.App1.DataAccess.SqlServer {

    [MetadataType(typeof(Country.MetaData))]
    public partial class Country {

        private class MetaData {

            [Required]
            [StringLength(50)]
            [DisplayName("Name of Country")]
            public string CountryName { get; set; }

            [Required]
            [StringLength(5)]
            [DisplayName("ISO 3166 Code of Country")]
            public string CountryISO3166Code { get; set; }

            [DisplayName("Is Country Approved?")]
            public string IsApproved { get; set; }

        }
    }
}

这篇关于实体框架4.1 - code先用现有的数据库,如何定义类,使用属性或EntityTypeConfiguration?有什么不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆