EntityValue

open class EntityValue: StructureBase

Encapsulates an OData entity value.

  • Decode the encoded data from the Decoder object and insantiate a new EntityValue object from it.

    See also

    EntityValue.encode(to encoder: Encoder) for usage examples how to encode and decode EntityValue

    Declaration

    Swift

    public required init(from decoder: Decoder) throws

    Parameters

    from

    decoder object which contains the original object’s serialized data in a container instance

  • Encode the object instance

    See also

    EntityValue.decode(to encoder: Encoder)

    Example of encode/decode of an EntityValue using proxy classes

    open func encodeEntityValueExample() throws -> Void {
    let provider = OnlineODataProvider(serviceName: "NorthwindService",
        serviceRoot: "http://services.odata.org/V4/Northwind/Northwind.svc/")
    let service = NorthwindService(provider: provider)
    
    // Download the entity by dynamic API which will be encoded
    let query = DataQuery()
    let entityValueToBeEncoded = try service.fetchEmployees(matching: query).first
    
    // Encode the EntityValue with JSONEncoder (other encoder exists such as PropertyListEncoder)
    let encoder = JSONEncoder()
    if let encodedEntityValue = try? encoder.encode(entityValueToBeEncoded) {
        if let json = String(data: encodedEntityValue, encoding: .utf8){
            print(json)
        }
    
        // Decoding
        // JSONDecoder is used, but other decoders are available, such as PropertyListDecoder
        let decoder = JSONDecoder()
        // Add typeInfo to the decoder
        decoder.userInfo[CSDLDocument.csdlInfoKey] = service.metadata
    
        // Decode
        let decodedEntityValue = try? decoder.decode(EntityValue.self,
            from: encodedEntityValue)
    }
    }
    

    Example of encode/decode of an EntityValue using dynamic API

    open func encodeEntityValueExample() throws -> Void {
        let provider = OnlineODataProvider(serviceName: "NorthwindService",
            serviceRoot: "http://services.odata.org/V4/Northwind/Northwind.svc/")
        let service = AnyDataService(provider: provider)
    
        // Explicitly load metadata, it must be cached manually. The reason is that type infos
        // will not be implicitly encoded. The dataservice's metadata contains all such infos,
        // so it must be cached, and parsed later at decoding.
        service.serviceOptions.csdlOptions = ( service.serviceOptions.csdlOptions |
            CSDLOption.retainResolvedText | CSDLOption.retainOriginalText )
        try service.loadMetadata()
        let metadataCachedAsString = service.metadata.resolvedText!
    
        // Get the entity to be encoded by dynamic API
        let peopleEntitySet = try service.entitySet(withName: "Employees")
        let query = DataQuery().from(peopleEntitySet)
        let entityValueToBeEncoded = try service.executeQuery(query).entityList().first
    
        // Encode the EntityValue with JSONEncoder (other encoder exists such as PropertyListEncoder)
        let encoder = JSONEncoder()
        if let encodedEntityValue = try? encoder.encode(entityValueToBeEncoded) {
            if let json = String(data: encodedEntityValue, encoding: .utf8){
                print(json) // Check
            }
    
            // Decoding
            // JSONDecoder is used, but other decoders are available, such as PropertyListDecoder
            let decoder = JSONDecoder()
    
            // Get type infos from cached metadata by parsing it to CSDLDocument
            let parser: CSDLParser = CSDLParser()
            parser.csdlOptions = (CSDLOption.processMixedVersions | CSDLOption.retainOriginalText |
                CSDLOption.resolveUndefinedTerms)
            var csdlDocument: CSDLDocument = parser.parseInProxy(metadataCachedAsString, url: "")
    
            // Add typeInfo to the decoder
            decoder.userInfo[CSDLDocument.csdlInfoKey] = csdlDocument
    
            // Decode
            let decodedEntityValue = try? decoder.decode(EntityValue.self, from: encodedEntityValue)
        }
    }
    

    Declaration

    Swift

    public override func encode(to encoder: Encoder) throws

    Parameters

    to

    encoder object which can be used to serialize the object’s data one by one into a container instance

  • Parent entity when this entity is to be created as a related child.

    Declaration

    Swift

    final public var parentEntity: EntityValue?
  • Parent property when this entity is to be created as a related child.

    Declaration

    Swift

    final public var parentProperty: Property?
  • Can be used to hold the last modified time for a changed entity.

    Declaration

    Swift

    final public var deltaTime: GlobalDateTime?
  • Construct a new entity value. This constructor is intended for use by custom entity value subclasses. Use ofType for regular construction.

    Declaration

    Swift

    public init(withDefaults: Bool = false, type: EntityType? = nil)

    Parameters

    withDefaults

    Should setDefaultValues be called to initialize properties with default values?

    type

    Entity type. Should not be nil except when called by generated proxy base classes.

  • Bind an entity to a property of the current entity. This can be used before DataService.updateEntity to update the bindings of navigation properties.

    Example using proxy classes

    open func bindEntityExample() throws -> Void {
        defer {
            DebugConsole.traceOut("example.NorthwindProxyClient.bindEntityExample")
        }
        do {
            DebugConsole.traceIn("example.NorthwindProxyClient.bindEntityExample")
            do {
                let service = self.service
                let categoryQuery = DataQuery().top(1).expand(Category.products)
                let category = try service.fetchCategory(matching: categoryQuery)
                let productQuery = DataQuery().top(1)
                let product = try service.fetchProduct(matching: productQuery)
                category.bindEntity(product, to: Category.products)
                try service.updateEntity(category)
            }
        }
    }
    

    Example using dynamic API

    open func bindEntityExample() throws -> Void {
        defer {
            DebugConsole.traceOut("example.NorthwindClient.bindEntityExample")
        }
        do {
            DebugConsole.traceIn("example.NorthwindClient.bindEntityExample")
            do {
                let service = self.service
                let categoriesEntitySet = service.entitySet(withName: "Categories")
                let productsEntitySet = service.entitySet(withName: "Products")
                let categoryEntityType = categoriesEntitySet.entityType
                let productsProperty = categoryEntityType.property(withName: "Products")
                let categoryQuery = DataQuery().from(categoriesEntitySet).top(1)
                    .expand(productsProperty)
                let category = try service.executeQuery(categoryQuery)
                    .requiredEntity()
                let productQuery = DataQuery().from(productsEntitySet).top(1)
                let product = try service.executeQuery(productQuery).requiredEntity()
                category.bindEntity(product, to: productsProperty)
                try service.updateEntity(category)
            }
        }
    }
    

    Declaration

    Swift

    open func bindEntity(_ entity: EntityValue, to: Property) -> Void

    Parameters

    entity

    Entity to be bound.

    to

    Property the entity will be bound to.

  • The canonical URL for this entity, relative to the service root URL. Uses OData V4 URL conventions.

    Declaration

    Swift

    open var canonicalURL: String
  • Declaration

    Swift

    open func copyEntity() -> EntityValue

    Return Value

    A copy of this entity value (only structural properties are copied).

  • Data type with a DataType.code of DataType.ENTITY_VALUE.

    Declaration

    Swift

    override open var dataType: DataType
  • The entity key for this value.

    Declaration

    Swift

    open var entityKey: EntityKey
  • The entity set for this value.

    See also

    inSet.

    Declaration

    Swift

    open var entitySet: EntitySet
  • The entity type metadata for this value (dataType cast to EntityType).

    Declaration

    Swift

    open var entityType: EntityType
  • Declaration

    Swift

    open class func equal(a: EntityValue?, b: EntityValue?) -> Bool

    Parameters

    a

    First entity value.

    b

    Second entity value.

    Return Value

    true if two entity values have equal structural properties.

  • Declaration

    Swift

    open class func equalKeys(a: EntityValue?, b: EntityValue?) -> Bool

    Parameters

    a

    First entity value.

    b

    Second entity value.

    Return Value

    true if two entity values have equal key properties.

  • true if this entity has binding-related changes.

    See also

    bindEntity, unbindEntity.

    Declaration

    Swift

    open var hasChangedBindings: Bool
  • Declaration

    Swift

    open func hasKey() -> Bool

    Return Value

    true if this entity has a value for all key properties.

  • true if this entity is in error state, for example due to the failed backend execution of an uploaded offline create/update/delete operation. If true, then one of isCreated, isUpdated or isDeleted should also be true to indicate the kind of failed operation. In some cases (e.g. system unable to distinguish create from update due to upsert behaviour) then isCreated, isUpdated and isDeleted might all be false.

    Declaration

    Swift

    open var inErrorState: Bool
  • Change the entity set for this entity. Having a non-null entity set is optional if only one entity set in the DataService uses the entity type, but is required (before DataService.createEntity is called) if multiple entity sets use the same entity type.

    Example using proxy classes

    open func createEntityInSetExample() throws -> Void {
        defer {
            DebugConsole.traceOut("example.NorthwindProxyClient.createEntityInSetExample")
        }
        do {
            DebugConsole.traceIn("example.NorthwindProxyClient.createEntityInSetExample")
            do {
                let service = self.service
                let customer = Customer()
                customer.companyName = "Voyager Inc."
                customer.contactName = "Kathryn Janeway"
                try service.createEntity(customer.inSet(NorthwindServiceMetadata.EntitySets.customers))
            }
        }
    }
    

    Example using dynamic API

    open func createEntityInSetExample() throws -> Void {
        defer {
            DebugConsole.traceOut("example.NorthwindClient.createEntityInSetExample")
        }
        do {
            DebugConsole.traceIn("example.NorthwindClient.createEntityInSetExample")
            do {
                let service = self.service
                let customersEntitySet = service.entitySet(withName: "Customers")
                let customerEntityType = customersEntitySet.entityType
                let companyNameProperty = customerEntityType.property(withName: "CompanyName")
                let contactNameProperty = customerEntityType.property(withName: "ContactName")
                let customer = EntityValue.ofType(customerEntityType)
                companyNameProperty.setStringValue(in: customer, to: "Voyager Inc.")
                contactNameProperty.setStringValue(in: customer, to: "Kathryn Janeway")
                try service.createEntity(customer.inSet(customersEntitySet))
            }
        }
    }
    

    Declaration

    Swift

    open func inSet(_ set: EntitySet) -> EntityValue

    Parameters

    set

    Entity set.

    Return Value

    This entity.

  • true if this entity has just been created in the local database or backend system.

    Declaration

    Swift

    open var isCreated: Bool
  • true if this entity has been newly instantiated with default property values.

    See also

    StructureBase.setDefaultValues.

    Declaration

    Swift

    open var isDefault: Bool
  • true if this entity has just been deleted from the local database or backend system.

    Declaration

    Swift

    open var isDeleted: Bool
  • true if a change (create, update or delete) has been submitted to the local database, but not yet synchronized to the backend system.

    Declaration

    Swift

    open var isLocal: Bool
  • true if this entity has been newly instantiated, but not yet created, updated or deleted in the local database or backend system.

    Declaration

    Swift

    open var isNew: Bool
  • Declaration

    Swift

    open func isNewOrChanged(property: Property) -> Bool

    Parameters

    property

    Structural property.

    Return Value

    true if the value of property property is new or changed, relative to oldEntity.

  • true if this object is an entity reference. If true, the editLink and/or readLink will be non-null, or the key properties will be available. Non-key properties will not be available.

    Declaration

    Swift

    open var isReference: Bool
  • true if this entity has just been updated in the local database or backend system.

    Declaration

    Swift

    open var isUpdated: Bool
  • Stream link for media entities. Should not be used with non-media entities.

    Declaration

    Swift

    open var mediaStream: StreamLink
  • Construct a new entity value of the specified type.

    Declaration

    Swift

    open class func ofType(_ type: EntityType) -> EntityValue

    Parameters

    type

    Entity type for the new value.

    Return Value

    A new entity value.

  • Contains the original values for all structural properties of this entity value. Used by DataService.updateEntity to determine the changed properties for PATCH requests.

    Declaration

    Swift

    open var oldEntity: EntityValue?
  • Remember the values of structural properties of this entity as the oldEntity.

    Declaration

    Swift

    open func rememberOld() -> Void
  • Convert this data value to a string. If the dataType is defined by XML Schema Part 2: Datatypes, then the corresponding lexical format is used. JSON format is used for structured values (arrays and objects).

    Declaration

    Swift

    override open func toString() -> String

    Return Value

    Lexical representation of this data value.

  • Data type code of the wrapped value, equivalent to dataType.code.

    Declaration

    Swift

    override open var typeCode: Int
  • Unbind an entity from a property of the current entity. This can be used before DataService.updateEntity to update the bindings of navigation properties.

    Example using proxy classes

    open func unbindEntityExample() throws -> Void {
        defer {
            DebugConsole.traceOut("example.NorthwindProxyClient.unbindEntityExample")
        }
        do {
            DebugConsole.traceIn("example.NorthwindProxyClient.unbindEntityExample")
            do {
                let service = self.service
                let categoryQuery = DataQuery().top(1).expand(Category.products)
                let category = try service.fetchCategory(matching: categoryQuery)
                let products = category.products
                if products.count != 0 {
                    let product = products.first!
                    category.unbindEntity(product, from: Category.products)
                }
                try service.updateEntity(category)
            }
        }
    }
    

    Example using dynamic API

    open func unbindEntityExample() throws -> Void {
        defer {
            DebugConsole.traceOut("example.NorthwindClient.unbindEntityExample")
        }
        do {
            DebugConsole.traceIn("example.NorthwindClient.unbindEntityExample")
            do {
                let service = self.service
                let categoriesEntitySet = service.entitySet(withName: "Categories")
                let categoryEntityType = categoriesEntitySet.entityType
                let productsProperty = categoryEntityType.property(withName: "Products")
                let categoryQuery = DataQuery().from(categoriesEntitySet).top(1)
                    .expand(productsProperty)
                let category = try service.executeQuery(categoryQuery)
                    .requiredEntity()
                let products = productsProperty.entityList(from: category)
                if products.length != 0 {
                    let product = products.first()
                    category.unbindEntity(product, from: productsProperty)
                }
                try service.updateEntity(category)
            }
        }
    }
    

    Declaration

    Swift

    open func unbindEntity(_ entity: EntityValue, from: Property) -> Void

    Parameters

    entity

    Entity to be unbound.

    from

    Property the entity will be unbound from.

  • Change the primary key for this entity.

    Declaration

    Swift

    open func withKey(_ key: EntityKey) -> EntityValue

    Parameters

    key

    Primary key

    Return Value

    This entity.