实体框架中的关系问题

时间:2012-05-12 11:28:54

标签: c# database asp.net-mvc sql-server-2008 entity-framework

我在EF v4中遇到麻烦。我知道这个问题非常受欢迎,我试图在互联网上找到一些东西,但它没有帮助。 我有类与地址(人有地址)一对一的人

class Person
{
public int PersonId{get;set;}
public string FisrtName{get; set;}
...
public int AddressId{get;set;}
public virtual Address Address{get;set;}
}
class Address
{
public int AddressId{get;set}
public string Street{get;set;}
...
}

我认为它是一对一的关系,我遵循EF v4中的所有约定。 但是当我创建生成DB的DB图时,我看不到Person和Address之间的任何关系。我的意思是我看到两个表没有关系上的人和关键字地址 另一个像这种关系的表创建了一对多的Account上的键和地址上的无穷大,但代码相同。我在设计师看到只有一对多的关联,有些情况我可以看到表之间的任何关系必须是。 请帮帮我!谢谢你的帮助 P.S我认为添加表格时设计师遇到了麻烦

2 个答案:

答案 0 :(得分:4)

如果您首先使用代码,则可以使用流畅的代码API或使用属性来优化模型来自定义持久性映射。如果您要使用简单的密钥名称(例如Id),EF可以通过推理来解决关系;在你的情况下,EF需要提示PersonID和AddressID是密钥。

要使用属性方法,请在项目中添加对System.ComponentModel.DataAnnotations的引用,并使用System.ComponentModel.DataAnnotations添加对应的''在您的源文件中根据需要。以下示例(EF 4.3.1)将生成"一对多"生成的地址和人员表之间的关系(在这种情况下,您不希望一对一)。运行代码后,您将在SQL Server数据库关系图窗口中看到关系。

class Program
{
    static void Main(string[] args)
    {
        using (ContactsEntities entities = new ContactsEntities())
        {
            Address doeaddress = new Address() { Street = "1 Broadway", ZipCode = "01234" };
            Address doeaddress2 = new Address() { Street = "2 Broadway", ZipCode = "01234" };
            entities.Addresses.Add(doeaddress);
            entities.Persons.Add(new Person() { FirstName = "Jane", LastName = "Doe", Address = doeaddress });
            entities.Persons.Add(new Person() { FirstName = "John", LastName = "Doe", Address = doeaddress });
            entities.Persons.Add(new Person() { FirstName = "Jim", LastName = "Doe", Address = doeaddress2 });
            entities.SaveChanges(); 
        }
        Console.WriteLine("Press Enter to exit...");
        Console.ReadLine();

    }
}

[Table("Addresses")]
public partial class Address
{
    public Address()
    {
        this.Persons = new HashSet<Person>();
    }
    [Key]
    public int AddressID { get; set; }
    [Required]
    public string Street { get; set; }
    [RegularExpression(@"^(\d{5}-\d{4}|\d{5}|\d{9})$")]
    [Required]
    public string ZipCode { get; set; }

    public virtual ICollection<Person> Persons { get; set; }
}

[Table("Persons")]
public partial class Person
{
    [Key]
    public int PersonID { get; set; }
    public int AddressID { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    [ForeignKey("AddressID")]
    public virtual Address Address { get; set; }
}

public partial class ContactsEntities : DbContext
{
    public DbSet<Address> Addresses { get; set; }
    public DbSet<Person> Persons { get; set; }
}

答案 1 :(得分:0)

根据反馈,这里是一对一(实际上是一对一或一对)关系的示例。我使用了流畅的API来设置OnModelCreating覆盖中的关系。在这种情况下,一个人最多可以有一个照片行。实际上,如果Photos表包含一个或多个用于保存图像数据的大字节数组,这可能很有用;为清晰起见,我使用字符串来表示图像的链接。

    static void Main(string[] args)
    {
        using (ContactsEntities entities = new ContactsEntities())
        {

            entities.Persons.Add(new Person() { FirstName = "Jane", LastName = "Doe", Photo = new Photo() { PhotoLink = "/images/jane.jpg" } });
            entities.Persons.Add(new Person() { FirstName = "John", LastName = "Doe" }); // no photo
            entities.Persons.Add(new Person() { FirstName = "Joe", LastName = "Smith", Photo = new Photo() { PhotoLink = "/images/joe.jpg", ThumnbnailLink = "/images/thumbs/joe.jpg" } });

            // note that the following is not allowed based on the defined RI rules - will fail on call to SaveChanges:
            // entities.Photos.Add(new Photo() { PhotoLink = "/images/as.jpg" });

            entities.SaveChanges();

            foreach (Person person in entities.Persons)
            {
                Console.WriteLine("{0} {1} {2}", person.FirstName, person.LastName, person.Photo == null ? "missing photo" : person.Photo.PhotoLink);
            } 
        }

        Console.WriteLine("Press Enter to exit...");
        Console.ReadLine();

    }
}

public partial class ContactsEntities : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // a Person may have at most one Photo
        modelBuilder.Entity<Person>().HasOptional<Photo>(p => p.Photo);
        // a Photo is dependant on a Person (non-nullable FK constraint)
        modelBuilder.Entity<Photo>().HasRequired<Person>(p => p.Person);
        base.OnModelCreating(modelBuilder);
    }
    public DbSet<Photo> Photos { get; set; }
    public DbSet<Person> Persons { get; set; }
}

[Table("Photos")]
public partial class Photo
{
    [Key]
    public int PhotoID { get; set; }
    [Required]
    public string PhotoLink { get; set; }
    public string ThumnbnailLink { get; set; }
    public virtual Person Person { get; set; }
}

[Table("Persons")]
public partial class Person
{
    [Key]
    public int PersonID { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }

    public virtual Photo Photo { get; set; }
}