如何引用非外键的对象

如何引用非外键的对象

本文介绍了代码优先数据注释 - 如何引用非外键的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自LINQ2SQL。我有一个对象"人物"它具有对象"地址"的引用。

I'm coming from the LINQ2SQL. I have an object "Person" that has a reference to object "Address".

下面的代码将生成两个表 - 一个带有fk到地址表的Person表。

The code below will generate two tables - a Person table with a fk to the Address table.

// LINQ2SQL
[Association(ThisKey = "AddressId", ... etc
Public EntityRef<Address> HomeAddress = new EntityRef<Address>();
// EF4
[ForeignKey("AddressId")]
public Address HomeAddress {...}

现在,使用LINQ2SQL,我也可以使用对Address对象的简单引用,这将生成一个表 - 一个Person表,其地址字段被非规范化为Person表。

Now, with LINQ2SQL, I can also use a plain reference to the Address object, and this will generate a single table - a Person table with the address fields denormalized into the Person table.

// LINQ2SQL
public Address HomeAddress() ...
// EF4 equivalent
// HELP? what do I put here?

我可以在EF4中这样做?我使用哪些数据注释?

Can I do this in EF4? What data annotations do I use?

感谢您的帮助,

Ray

Thank you for your help,
Ray

 

推荐答案

modelBuilder.ComplexType<Address>();

您不需要在您的实体中执行任何特殊操作。以下是完整的示例:

You don't need to do anything special in your entity. Here is the full example:

重要的是要记住复杂的属性

One thing that is important to remember that complex property

  public class CustomersDB : DbContext
  {
    public DbSet<Customer> Customers { get; set; }
  }

  public class Customer
  {
    public int ID { get; set; }
    public string Name { get; set; }
    public Address HomeAddress { get; set; }
  }

  public class Address
  {
    public string Street { get; set; }
    public string City { get; set; }
  }

  public static void Main()
  {
    using (var ctx = new CustomersDB())
    {
      ctx.Customers.Add(new Customer()
      {
        ID = 1,
        Name = "Test",
        HomeAddress = new Address()
        {
          Street = "1st NE",
          City = "Seattle"
        }
      });

      ctx.SaveChanges();
    }
  } 

值得一提的有关复杂属性的一件事是复杂属性不能为空。如果complex属性的所有子属性都为null,但复杂属性本身不能为null,则完美无缺。否则,当您尝试将实体保存到数据库时,您将获得
异常。

One thing about complex properties that is worth mentioning is that complex properties must not be null. It is perfectly if all the child properties of the complex property are null but the complex property itself must not be null. Otherwise you will get an exception when trying to save the entity to the database.

Pawel

 

 


这篇关于代码优先数据注释 - 如何引用非外键的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 00:43