ResourceModel.cs 2.19 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
                Url = resourceObject.Url,
24
                DisplayName = resourceObject.DisplayName,
L. Ellenbeck's avatar
L. Ellenbeck committed
25 26
                TypeId = resourceObject.Type.Id,
                Type = new ResourceTypeModel().GetById(resourceObject.Type.Id)
27 28 29 30 31
            };
            Insert(resource);
            return resource;
        }

32 33 34 35 36 37 38
        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"
39 40
                            && (relation.Project.ProjectResourceProjectIdIds != null && relation.Project.ProjectResourceProjectIdIds.
                                Any((projectResource) => projectResource.Resource == resource))
41 42 43 44
                        select relation).Any();
            });
        }

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

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

L. Ellenbeck's avatar
L. Ellenbeck committed
55
        public override void SetObjectId(Resource databaseObject, Guid id)
56
        {
L. Ellenbeck's avatar
L. Ellenbeck committed
57
            databaseObject.Id = id;
58
        }
59 60 61 62 63 64 65 66 67

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

            return Update(resource);
        }
68 69
    }
}