ResourceModel.cs 2.14 KB
Newer Older
1
using Coscine.Api.Project.ReturnObjects;
2
using Coscine.ApiCommons.Models;
3
using Coscine.Database.Model;
4 5 6
using LinqToDB;
using System;
using System.Linq;
7
using System.Linq.Expressions;
8 9 10 11 12

namespace Coscine.Api.Project.Models
{
    public class ResourceModel : DatabaseModel<Resource>
    {
13
        public ResourceModel() : base(Program.Configuration)
14 15 16 17
        {

        }

18 19 20 21 22
        public Resource StoreFromObject(ResourceObject resourceObject)
        {
            Resource resource = new Resource()
            {
                ExternalId = resourceObject.ExternalId,
23 24
                Url = resourceObject.Url,
                TypeId = resourceObject.Type.Id
25 26 27 28 29 30
            };
            resource.Type = new ResourceTypeModel().GetById(resourceObject.Type.Id);
            Insert(resource);
            return resource;
        }

31 32 33 34 35 36 37
        public bool OwnsResource(User user, Resource resource)
        {
            return DatabaseConnection.ConnectToDatabase((db) =>
            {
                return (from relation in db.ProjectRoles
                        where relation.User == user
                            && relation.Role.DisplayName == "Owner"
38 39
                            && (relation.Project.ProjectResourceProjectIdIds != null && relation.Project.ProjectResourceProjectIdIds.
                                Any((projectResource) => projectResource.Resource == resource))
40 41 42 43
                        select relation).Any();
            });
        }

44
        public override Expression<Func<Resource, Guid>> GetIdFromObject()
45
        {
46
            return databaseObject => databaseObject.Id;
47 48 49 50 51 52
        }

        public override ITable<Resource> GetITableFromDatabase(CoscineDB db)
        {
            return db.Resources;
        }
53 54 55 56 57

        public override void SetObjectId(Resource databaseObject, Guid Id)
        {
            databaseObject.Id = Id;
        }
58 59 60 61 62 63 64 65 66

        public int UpdateByObject(Resource resource, ResourceObject resourceObject)
        {
            resource.ExternalId = resourceObject.ExternalId;
            resource.TypeId = resourceObject.Type.Id;
            resource.Url = resourceObject.Url;

            return Update(resource);
        }
67 68
    }
}