1

我有一个带有 Entity Framework 7 的 Asp.Net 项目,我有一个带有附件列表的电子邮件类。

我不想让任何人将项目添加到我的列表中,我有

private List<Attachment> Resources { get; set; } public IEnumerable<Attachment> Attachments { get; set; }

现在,我想将与属性资源而不是附件的关系映射到数据库。

Entity Framework 7 出现异常...

我怎么能做到这一点。

4

2 回答 2

0

我同意伊泰的观点。

也许这个代码示例可以帮助你。

制作映射到 db 表的实体。

public class EmailState
{
    public int Id { get; private set; }

    public List<AttachmentState> Resources { get; set; }

    public static Email ToEmail(EmailState state)
    {
        return new Email(state);
    }
}

public class AttachmentState
{
    public static Attachment ToAttachment(AttachmentState state)
    {
        return new Attachment(state);
    }

    public Attachment ToAttachment()
    {
        return new Attachment(this);
    }
}

制作可供用户使用的课程

public class Email
{
    public Email()
    {
        this.State = new EmailState();
    }

    internal Email(EmailState state)
    {
        this.State = state;
    }

    internal EmailState State { get; set; }

    public int Id { get; private set; }

    public IEnumerable<Attachment> Attachments()
    {
        return this.State.Resources.Select(x => x.ToAttachment());
    }

    public void AddAttachment(Attachment attachment)
    {
        this.State.Resources.Add(attachment.State);
    }      
}

public class Attachment
{
    public Attachment()
    {
        this.State = new AttachmentState();
    }

    internal Attachment(AttachmentState state)
    {
        this.State = state;
    }

    internal AttachmentState State { get; set; }
}

定义 DbContext

public class EmailDbContext : DbContext
{
    public DbSet<EmailState> Emails { get; set; }
    public DbSet<AttachmentState> Attachments { get; set; }
}

制作存储库

public interface IEmailRepository
{
    void Add(Email email);

    Email GetById(int emailId);
}

public class EmailRepository : IEmailRepository
{
    private EmailDbContext _context;

    public EmailRepository(EmailDbContext context)
    {
        _context = context;
    }

    public void Add(Email email)
    {
        _context.Emails.Add(email.State);
    }

    public Email GetById(int emailId)
    {
        EmailState emailState = _context.Emails.Single(x => x.Id == emailId);

        return new Email(emailState);
    }
}

像这样使用它

using (var context = new EmailDbContext())
{
    IEmailRepository repository = new EmailRepository(context);

    var email = new Email();

    repository.Add(email);

    context.SaveChanges();

    var emailFoundById = repository.GetById(email.Id);
}
于 2016-12-16T15:20:07.527 回答
0

将 this 分为两个不同的模型,一个映射到数据库的内部模型和另一个可供用户使用的模型。这也是在层之间传递数据的正确方式。

希望能帮助到你!

于 2016-07-14T19:15:29.210 回答