地图私有财产

时间:2016-07-14 19:05:10

标签: c# entity-framework-core asp.net5

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

我不想离开任何人在我的列表中添加项目,我有

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

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

实体框架7引发例外......

我如何做到这一点。

2 个答案:

答案 0 :(得分:0)

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

希望它有所帮助!

答案 1 :(得分:0)

我同意Itay。

也许这段代码示例可以帮到你。

创建映射到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);
}