简体   繁体   中英

How to add new value with generic Repository if there are foreign keys (EF-4)?

i try to write a kind of generic repository to add method. Everything is ok to add but I have table which is related with two tables with FOREIGN KEY.But Not working because of foreign key

替代文字

public class DomainRepository<TModel> : IDomainRepository<TModel> where TModel : class
{
    private ObjectContext _context;
    private IObjectSet&#60;TModel&#62; _objectSet;

    public DomainRepository(ObjectContext context)
    {
        _context = context;
        _objectSet = _context.CreateObjectSet&#60;TModel&#62;();
    }

    // do something...
    public TModel Add<TModel>(TModel entity) where TModel : IEntityWithKey
    {
        EntityKey key = _context.CreateEntityKey(entity.GetType().Name, entity);          
        _context.AddObject(key.EntitySetName, entity);
        _context.SaveChanges();
        return entity;
    }
    // do something...
}

Calling Repository:

// insert-update-delete
public partial class AddtoTables
{
    public table3 Add(int TaskId, int RefAircraftsId)
    {
        using (DomainRepository<table3> repTask = new DomainRepository<table3>(new TaskEntities()))
        {
           return repTask.Add&#60;table3&#62;(new table3() { TaskId = TaskId, TaskRefAircraftsID = RefAircraftsId  });
        }
    }
}

How to add a new value if this table includes foreign key relation?

替代文字

Damn hard to be sure answer is going to be helpful cause I dont think I udnerstand your interface clearly but in order to add objects with foreign keys to generic repositary you will have to add support to add object with foreign keys. I think if you have something like params ForeignKey[] somewhere in signatures you will make a step towards having support objects with foreign keys. Probably advice is worthless, but I got a worthy advice.

Read Patterns of Enterprise Application Architecture by Martin Fowler and it will answer all of your questions - in this I am sure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM