powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / ADO.NET, LINQ, Entity Framework, NHibernate, DAL, ORM [игнор отключен] [закрыт для гостей] / Получить EntityObject из обьекта типа object
8 сообщений из 8, страница 1 из 1
Получить EntityObject из обьекта типа object
    #36558378
IPmen
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
У меня есть класс
Код: plaintext
1.
2.
3.
4.
    public class Repository<E, C> : IRepository<E, C>, IDisposable
        where E : EntityObject
        where C : ObjectContext
    {
в котором имееться метод
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
        public E SelectByKey(int Key)
        {
            var xParam = Expression.Parameter(typeof(E), typeof(E).Name);
            MemberExpression leftExpr = MemberExpression.Property(xParam, this._KeyProperty);
            Expression rightExpr = Expression.Constant(Key);
            BinaryExpression binaryExpr = MemberExpression.Equal(leftExpr, rightExpr);
            Expression<Func<E, bool>> lambdaExpr =
            Expression.Lambda<Func<E, bool>>(binaryExpr,
            new ParameterExpression[] { xParam });
            List<E> resultCollection = ((IRepository<E, C>)this).SelectAll(new Specification<E>(lambdaExpr));
            if (null != resultCollection && resultCollection.Count() > 0)
            {
                return resultCollection.First<E>();
            }
            return null;
        }
Создаю обьект с конкретным типом
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
    public class CityManagement
    {
        #region Global members

        Repository<City, Entities> CityRepository = null;

        Entities _ctx = new Entities();
        #endregion

        public CityManagement()
        {
           CityRepository = new Repository<City, Entities>(_ctx);
        }
        public City GetObjectByKey(int key)
        {
            return CityRepository .SelectByKey(key);
        }

    }
и всё нормально работает. Но хочется сделать один метод для всех типов. Т.е. я так понимаю мне нужна из моего обьекта типа object вытащить его EntityObject. можно ли как то это реализовать?
...
Рейтинг: 0 / 0
Получить EntityObject из обьекта типа object
    #36558689
qu-qu
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
IPmen... Но хочется сделать один метод для всех типов.
...
Что-то типа так (Repository<K> ничего не знает о типах, которые он хранит и отдает, и метод у него один на всех):
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
using System;
using System.Linq;

public class Script
{
    public static void Main(string[] args)
    {
        var foo_context = new Foo[] { new Foo(1), new Foo(2), new Foo(3), new Foo(4) }
            .AsQueryable<IEntity<int>>();
        var foo_repo = new Repository<int>(foo_context);
        var foo = foo_repo.GetEntityByKey(2);
        Console.WriteLine("foo = {0}", foo == null ? "null" : foo.ToString());
        foo = foo_repo.GetEntityByKey(22);
        Console.WriteLine("foo = {0}", foo == null ? "null" : foo.ToString());
        var bar_context = new Bar[] { new Bar(1), new Bar(2), new Bar(3), new Bar(4) }
            .AsQueryable<IEntity<int>>();
        var bar_repo = new Repository<int>(bar_context);
        var bar = bar_repo.GetEntityByKey(2);
        Console.WriteLine("bar = {0}", bar == null ? "null" : bar.ToString());
        bar = bar_repo.GetEntityByKey(22);
        Console.WriteLine("bar = {0}", bar == null ? "null" : bar.ToString());
        Console.ReadLine();
    }
}

public interface IEntity<T>
{
    T Key { get; set; }
}

public abstract class IntEntity : IEntity<int>
{
    public int Key { get; set; }
}

public class Foo : IntEntity
{

    public Foo(int key) { Key = key; }

    public override string ToString()
    {
        return string.Format("[Foo: {0}]", Key);
    }
}

public class Bar : IntEntity
{

    public Bar(int key) { Key = key; }

    public override string ToString()
    {
        return string.Format("[Bar: {0}]", Key);
    }
}

public interface IRepository<T, K> where T : IEntity<K>
{
    T GetEntityByKey(K key);
}

public class Repository<K> : IRepository<IEntity<K>, K>
{

    private IQueryable<IEntity<K>> _ctx;
    public Repository(IQueryable<IEntity<K>> ctx) { _ctx = ctx; }

    public IEntity<K> GetEntityByKey(K key) {
		return _ctx.FirstOrDefault<IEntity<K>>(e => e.Key.Equals(key));
	}
}
...
Рейтинг: 0 / 0
Получить EntityObject из обьекта типа object
    #36558914
qu-qu
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
IPmen,

Вот, немного "причесал" с менеджерами и строгой типизацией обслуживаемых сущностей:
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
using System;
using System.Linq;

public class Script
{
    public static void Main(string[] args)
    {
        var foo_man = new FooManager();
        var foo = foo_man.GetEntityByKey(2);
        Console.WriteLine("foo = {0}, {1}", foo == null ? "null" : foo.ToString(), foo.Zoo);
        foo = foo_man.GetEntityByKey(22);
        Console.WriteLine("foo = {0}", foo == null ? "null" : foo.ToString());

        var bar_man = new BarManager();
        var bar = bar_man.GetEntityByKey(2);
        Console.WriteLine("bar = {0}, {1}", bar == null ? "null" : bar.ToString(), bar.Baz);
        bar = bar_man.GetEntityByKey(22);
        Console.WriteLine("bar = {0}", bar == null ? "null" : bar.ToString());
        Console.ReadLine();
    }
}

public interface IEntity<T>
{
    T Key { get; set; }
}

public abstract class IntEntity : IEntity<int>
{
    public int Key { get; set; }
}

public class Foo : IntEntity
{

    public Foo(int key) { Key = key; Zoo = "zoo"; }

    public string Zoo { get; set; }

    public override string ToString()
    {
        return string.Format("[Foo: {0}, {1}]", Key, Zoo);
    }
}

public class Bar : IntEntity
{

    public Bar(int key) { Key = key; Baz = "baz"; }

    public string Baz { get; set; }

    public override string ToString()
    {
        return string.Format("[Bar: {0}, {1}]", Key, Baz);
    }
}

public interface IRepository<T, K> where T : IEntity<K>
{
    T GetEntityByKey(K key);
}

public abstract class Repository<T, K> : IRepository<T, K> where T : IEntity<K>
{
    private IQueryable<T> _ctx;
    public Repository() { _ctx = CreateContext(); }

    protected abstract IQueryable<T> CreateContext();

    public T GetEntityByKey(K key)
    {
        if (_ctx == null)
            return default(T);
        return _ctx.FirstOrDefault<T>(e => e.Key.Equals(key));
    }
}

public class FooManager : Repository<Foo, int>
{
    protected override IQueryable<Foo> CreateContext()
    {
        return new Foo[] { new Foo(1), new Foo(2), new Foo(3), new Foo(4) }
            .AsQueryable();
    }
}

public class BarManager : Repository<Bar, int>
{
    protected override IQueryable<Bar> CreateContext()
    {
        return new Bar[] { new Bar(1), new Bar(2), new Bar(3), new Bar(4) }
            .AsQueryable();
    }
}
...
Рейтинг: 0 / 0
Получить EntityObject из обьекта типа object
    #36559014
qu-qu
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
qu-qu,

Гы-гы, "кому не спится в ночь глухую?" (с).
А вот странный "трюк" с выведением типов между Entity и Key (это когда не хочется писать на каждый Foo - отдельный FooManager):
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
using System;
using System.Linq;

public class Script
{
    public static void Main(string[] args)
    {
        var foo_man = new EntityManager<Foo>(Foo.FakeContext);
        var foo = foo_man.GetEntityByKey(2);
        Console.WriteLine("foo = {0}, {1}", foo == null ? "null" : foo.ToString(), foo.Zoo);
        foo = foo_man.GetEntityByKey(22);
        Console.WriteLine("foo = {0}", foo == null ? "null" : foo.ToString());

        var bar_man = new EntityManager<Bar>(Bar.FakeContext);
        var bar = bar_man.GetEntityByKey(Bar.FakeContext.ToArray()[2].Key);
        Console.WriteLine("bar = {0}, {1}", bar == null ? "null" : bar.ToString(), bar.Baz);
        bar = bar_man.GetEntityByKey(new Guid());
        Console.WriteLine("bar = {0}", bar == null ? "null" : bar.ToString());
        Console.ReadLine();
    }
}

public interface IEntity<K>
{
    K Key { get; set; }
}

public abstract class IntEntity : IEntity<int>
{
    public int Key { get; set; }
}

public abstract class GuidEntity : IEntity<Guid>
{
    public Guid Key { get; set; }
}

public class Foo : IntEntity
{
    public Foo(int key) { Key = key; Zoo = "zoo" + new Random().Next().ToString("0x"); }
    public string Zoo { get; set; }
    public override string ToString()
    {
        return string.Format("[Foo: {0}, {1}]", Key, Zoo);
    }
    public static IQueryable<Foo> FakeContext
    {
        get
        {
            return new[] { new Foo(1), new Foo(2), new Foo(3), new Foo(4) }.AsQueryable();
        }
    }
}

public class Bar : GuidEntity
{
    public Bar() { Key = Guid.NewGuid(); Baz = "baz" + Key.ToString(); }
    public string Baz { get; set; }
    public override string ToString() { return string.Format("[Bar: {0}, {1}]", Key, Baz); }
    private static IQueryable<Bar> _fake_ctx;
    public static IQueryable<Bar> FakeContext
    {
        get
        {
            if (_fake_ctx == null)
                _fake_ctx = new[] { new Bar(), new Bar(), new Bar(), new Bar() }.AsQueryable();
            return _fake_ctx;
        }
    }
}

public interface IRepository<E, K> where E : IEntity<K>
{
    E GetEntityByKey(K key);
}

public class Repository<E, K> : IRepository<E, K> where E : IEntity<K>
{
    private IQueryable<E> _ctx;
    public Repository(IQueryable<E> context) { _ctx = context; }

    public E GetEntityByKey(K key)
    {
        if (_ctx == null)
            return default(E);
        return _ctx.FirstOrDefault<E>(e => e.Key.Equals(key));
    }
}

public class EntityManager<E>
{
    private IQueryable<E> _ctx;
    public EntityManager(IQueryable<E> context)
    {
        _ctx = context;
    }
    public E GetEntityByKey<K>(K key)
    {
        if (typeof(IEntity<K>).IsAssignableFrom(typeof(E)))
        {
            var repo = new Repository<IEntity<K>, K>(_ctx.Cast<IEntity<K>>());
            return (E)repo.GetEntityByKey(key);
        }
        else
            throw new ApplicationException(
                string.Format("A type of '{0}' must be assignable from a type of '{1}'."
                    ,typeof(E),typeof(IEntity<K>)));
    }
}
...
Рейтинг: 0 / 0
Получить EntityObject из обьекта типа object
    #36559277
Silverlight
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Откройте для себя DI контейнеры, многие вещи станут гораздо проще. С ними IntEntity, GuidEntity, еtc не нужны. Регистрируем в контейнере с нужными типами и все
...
Рейтинг: 0 / 0
Получить EntityObject из обьекта типа object
    #36559526
qu-qu
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
SilverlightОткройте для себя DI контейнеры, многие вещи станут гораздо проще. С ними IntEntity, GuidEntity , еtc не нужны. Регистрируем в контейнере с нужными типами и все
SeVa, это мне?
(сужу по упоминаниям имен классов из моих примеров).

Не стоит напрягаться, DI контейнеры я "открыл" для себя уже давно (боялся топик-кастеру приводить примеры решений с ними, судя по уровню вопроса), а данный код набросал сюда в качестве умозрительного примера - "как можно обращаться с репозиториями заранее неизвестных типизированных сущностей"...
(не без косяков, ес-с-нно, особенно в 2:40 ночи, но суть одна - это не "готовые решения", а просто - "концепты").

З.Ы. если желаете продолжить обсуждение в русле "доводки" до продуктивного решения - всегда готов...
...
Рейтинг: 0 / 0
Получить EntityObject из обьекта типа object
    #36559673
Silverlight
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Есть более общий паттерн - ISpecification.
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
 public IEnumerable<Entity> GetBySpec<TEntity>(ISpecification<TEntity> specification) where TEntity : class,TEntity, new()
{
            if (specification == (ISpecification<Entity>)null)
                throw new ArgumentNullException("specification");

            TraceManager.TraceInfo(
                           string.Format(CultureInfo.InvariantCulture,
                                        Resources.Messages.trace_GetBySpec,
                                        typeof(TEntity).Name));

            return (_context.CreateObjectSet<TEntity>()
                            .OfType<TEntity>()
                            .Where(specification.SatisfiedBy())
                            .AsEnumerable<TEntity>());
        }
Применим для произвольных выборок, составных ключей, может содержать дополнительные Include.
...
Рейтинг: 0 / 0
Получить EntityObject из обьекта типа object
    #36594334
IPmen
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
       
    public List<E> SelectAll(string entitySetName, ISpecification<E> where)
        {
            return DoQuery(entitySetName, where).ToList();
        }

 public interface ISpecification<E>
    {
        /// <summary>
        /// Select/Where Expression
        /// </summary>
        Expression<Func<E, bool>> EvalPredicate { get; }
        /// <summary>
        /// Function to evaluate where Expression
        /// </summary>
        Func<E, bool> EvalFunc { get; }
    }
Помогите пожалуйста. В каком виде мне передать параметр where?
...
Рейтинг: 0 / 0
8 сообщений из 8, страница 1 из 1
Форумы / ADO.NET, LINQ, Entity Framework, NHibernate, DAL, ORM [игнор отключен] [закрыт для гостей] / Получить EntityObject из обьекта типа object
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]