OData 4中$ref的意义是什么?$ref与$expand有何区别?
$ref and How It Differs from $expand Hey there! Since you're just dipping your toes into OData, let's break these two concepts down with plain language and examples to make things click.
1. What is $ref in OData 4?
$ref is OData's go-to tool for managing relationships between entities—think of it as handling the "digital links" connecting related data, like a customer and their orders. Instead of dealing with the actual entity data (like order amounts or customer emails), $ref focuses solely on the references (URLs) that tie entities together via navigation properties.
Here’s what you can do with it:
- Fetch references: Get the URLs of entities linked to a parent entity. For example, to see all order references tied to customer ID 1:
The response will be a list of reference URLs likeGET /Customers(1)/Orders/$ref{"@odata.id": "/Orders(101)"}—no full order details, just the links. - Add a reference: Link an existing entity to another without duplicating data. If you want to assign order 101 to customer 1:
POST /Customers(1)/Orders/$ref Content-Type: application/json {"@odata.id": "/Orders(101)"} - Delete a reference: Remove the link between two entities (this doesn’t delete the entities themselves, just the relationship). To unlink order 101 from customer 1:
DELETE /Customers(1)/Orders/$ref?$id=/Orders(101)
2. Key Differences Between $ref and $expand
These two serve totally distinct purposes—let’s break them down side by side:
Core Goal
$ref: Manages the relationships (links) between entities. It’s about creating, reading, or removing connections themselves.$expand: Fetches related entity data alongside the main entity in a single query. It’s about cutting down on API round trips by getting all needed data at once.
What They Return
$ref: Only returns the URLs of linked entities (the references), no actual entity properties like order dates or customer addresses.$expand: Returns the full data of linked entities embedded in the main entity’s response. For example:
This gives you the full customer object, plus anGET /Customers(1)?$expand=OrdersOrdersarray with all the order details tied to that customer.
Supported Operations
$ref: Works with GET (read references), POST (add links), and DELETE (remove links) operations.$expand: Only used with GET queries—you can’t use it to modify relationships.
Use Cases
- Use
$refwhen you need to:- Check which entities are linked to another without loading their full data
- Attach an existing entity to another (e.g., assign a pre-existing order to a new customer)
- Remove a link between entities without deleting either entity
- Use
$expandwhen you need to:- Get a parent entity and all its related data in one go (e.g., customer info + their orders)
- Avoid making multiple separate API calls to fetch related data
- Use
内容的提问来源于stack exchange,提问作者ananth sharma

