2012-03-01 49 views

回答

0

EF CF是一个基于代码的ORM(对象关系映射器)。它处理在应用程序中的类中存储和检索数据库中表的数据。

如果您想要从表单中存储/检索数据,您应该创建“模型”类 - 这些只是包含要存储在数据库中的值的属性的简单类。例如:

public class Page 
{ 
    public Guid ID {get; set;} 
    public string Title {get; set;} 
    public string Body {get; set;} 
    public string FontName {get; set;} 
    public int FontSize {get; set;} 
} 

然后,您可以创建一个包含您的模型类的类型DbSet实例一的DbContext类:

public class StorageContext : DbContext 
{ 
    public DbSet<Page> Pages {get; set;} 
} 

现在,EF会弄清楚的数据结构要存储并处理所有数据库操作以将数据加载/存储到数据库。

您应该可以编写几乎所有的模型和数据库代码(在需要重用的情况下,在单独的库中)。

注:我也强烈建议你增加一些抽象的附加水平,并创建一个库类,以便您的UI代码需要什么都不知道如何你存储你的数据 - 这将允许您更改到一个完全不同的存储引擎后来无需触摸您的应用程序代码!例如:

public class PageRepo 
{ 
    StorageContext _ctx = new StorageContext(); 

    public Page GetPageById(Guid id) 
    { 
     ... 
    } 

    public void StorePage(Page page) 
    { 
     ... 
    } 
} 

然后你用你的StorageContext(或者更好的是,你的资料库)和模型类从/到您的数据库获取/存储数据,并将这些值复制到必要的字段在表单中,peprforming在您存储数据之前进行任何数据验证,当然;)

HTH。

+0

答案太泛泛。 – Eranga 2012-03-02 00:34:18

0

实体框架允许您只映射几个预定义的类型。这是因为它是一个ORM,并且支持许多RDBMS常见的数据类型。您可以如何将复杂类型(如Font)分解为其基本属性并映射到实体。

public class Style 
{ 
    public Guid ID {get; set;} 
    public string FontName {get; set;} 
    public int FontSize {get; set;} 
    // other properties 
} 

在你的UI层你将有一个TextBox将使用样式打造字体。

public class TextBox 
{ 
    public TextBox(Style style) 
    { 
     Style = style; 
    } 
    protected Style Style {get; set;} 

    public Font FontSize { get { return new Font(Style.FontName, Style.FontSize); } } 
    // other properties 
}