使用Entity Framework或Linq将字符串的集合映射到SQL [英] Mapping collection of strings with Entity Framework or Linq to SQL

查看:116
本文介绍了使用Entity Framework或Linq将字符串的集合映射到SQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以将1数据库关系映射为父对象类上的基元数组。例如,假设我有一个数据库如下:

I would like to know if it is possible to map a 1-many database relationship as an array of primitives on the parent object class. For example, say I have a database as follows:

TABLE: PERSON
    ID - int

TABLE: PERSON_EMAIL_ADDRESSES
    PERSON_ID - int
    EMAIL_ADDRESS - string

我的个人课程,我想要有以下内容:

For my Person class, I'd like to have the following:

public class Person 
{
    public int ID { get; set; }
    public string[] EmailAddresses { get; set; }
}

默认的Linq to SQL&实体框架行为将是给我一个单独的类PERSON_EMAIL_ADDRESSES表,并在Person对象上的类型的集合...这是我不想要的。

The default Linq to SQL & Entity Framework behavior would be to give me a separate class for the PERSON_EMAIL_ADDRESSES table, and a collection of that type on the Person object...which is what I don't want.

看起来像这样可以使用NHibernate来完成,如 here 所述有没有办法使用EF或Linq to SQL?

Looks like this can be done with NHibernate as described here, but is there any way to do this with either EF or Linq to SQL?

提前感谢
Wayne

Thanks in advance, Wayne

推荐答案

如果你想要一个只读列表,就像你的NHibernate示例一样,你应该像往常一样映射,然后项目:

If you want a read-only list, as with your NHibernate sample, you should map as usual and then project:

var q = from p in Context.People
        select new Person // Where this is your Person type above, not a mapped entity type
        {
            ID = p.ID, 
            EmailAddresses = from pea in p.EmailAddresses
                             select pea.EmailAddress
        };

这在L2S和L2E两者中都有效。如果你想要读写,那么你需要 ID。

This works in both L2S and L2E. If you want read-write, then you need the ID.

这篇关于使用Entity Framework或Linq将字符串的集合映射到SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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