快捷搜索:

EF处理实体complex属性示例

这一篇先容一下Code First措施中,实体Complex属性的处置惩罚。Complex属性是将一个工具做为另一个工具的属性。映射到数据库中则子工详细现为多个属性字段。

反之,也便是说,数据库中多个相关字段映射成一个子工具,来进行统一的治理。

complex属性要留意不合于外键引用工具的。

下面用Code First的要领先做个complex属性。

public class Book

{public int BookId { get; set; }

public string BookTitle { get; set; }public Publisher Publisher { get; set; }

}

[ComplexType]public class Publisher

{public string PublisherName { get; set; }

public string PublisherAddress { get; set; }}

public class BookDbContext : DbContext

{public BookDbContext() : base("BookDB") {

Database.SetInitializer(new DropCreateDatabaseIfModelChanges()

);}

public IDbSet Books { get; set; }}

在上面的代码中,构造了一个Book实体,包孕一个complex属性publiser,Pubisher被标清楚明了是ComplexType

创建数据库,并添加一条测试记录

using (BookDbContext db = new BookDbContext())

{

Book newbook = new Book(){

BookTitle = "EF4.1 step by step",Publisher = new Publisher()

{PublisherName = "机器工业",

PublisherAddress = "北京"}

};db.Books.Add(newbook);

db.SaveChanges();

}

创建后的数据库如图示:

可以清楚的看到,complex属性作数据库的多个字段存在,命名款式为ComplexType.Property

直接获取属性值

第一种措施

var book = db.Books.Find(1);

///直接获取complex属性的某个详细属性值var pubName = db.Entry(book).Property(b => b.Publisher.PublisherName).CurrentValue;

Console.WriteLine(pubName);

第二种措施:

var pubName1 = db.Entry(book)

.ComplexProperty(b => b.Publisher).Property(p => p.PublisherName).CurrentValue;

Console.WriteLine(pubName1);

第三种措施:

var pubName2 = db.Entry(book).Property("Publisher.PublisherName").CurrentValue;

Console.WriteLine(pubName2.ToString());

获取complex属性工具

///获取繁杂属性工具

var pub = db.Entry(book).ComplexProperty

(b=>b.Publisher).CurrentValue;Console.WriteLine(pub.PublisherName);

假如要整个输出所有属性,这里也供给一个措施

public static void WritePropertyValues(string parentPropertyName, DbPropertyValues propertyValues)

{foreach (var propertyName in propertyValues.PropertyNames)

{var nestedValues = propertyValues[propertyName] as DbPropertyValues;

if (nestedValues != null){

WritePropertyValues(parentPropertyName + propertyName + ".", nestedValues);}

else{

Console.WriteLine("Property {0}{1} has value {2}",parentPropertyName, propertyName,

propertyValues[propertyName]);}

}}

调用这个措施的要领如下:

WritePropertyValues("", db.Entry(book).CurrentValues);

您可能还会对下面的文章感兴趣: